zoukankan      html  css  js  c++  java
  • Leetcode Remove Duplicates from Sorted List II

    Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.

    For example,
    Given 1->2->3->3->4->4->5, return 1->2->5.
    Given 1->1->1->2->3, return 2->3.

    只需要遍历链表,如果是相同元素则删除,如果不是删除元素保留即可

    #include <iostream>
    #include <string>
    #include <algorithm>
    
    using namespace std;
    
    struct ListNode{
        int val;
        ListNode *next;
        ListNode(int x): val(x), next(NULL){}
    };
    
    ListNode *deleteDuplicates(ListNode *head){
        if(head == NULL  ||  head->next  == NULL) return head;
        ListNode *newHead = new ListNode(-1);  //添加新的头结点
        ListNode *pre = newHead,*p = head;
        while(p){
            ListNode *q = p;
            int cnt = 0;
            while(q && q->val == p->val){
                cnt++;
                q = q->next;
            }
            if(cnt == 1){
                p->next = pre->next;
                pre->next = p;
                pre = p;
            }
            p = q;
            q = p;
        }
        ListNode *res = newHead->next;
        delete newHead;
        return res;
    }
    
    
    void printList(ListNode *head){
        while(head){
            cout<<"-->"<<head->val;
            head = head->next;
        }
        cout<<endl;
    }
    
    int main(){
        ListNode *head = new ListNode(1);
       ListNode *p = new ListNode(2);
       head->next = p;
       ListNode *q = new ListNode(2);
       p->next = q;
        printList(deleteDuplicates(head));
    }
  • 相关阅读:
    CXB 闯关游戏
    CXB 移动“哨兵棋子”
    GHOJ 300 Hanoi塔
    攻防世界 web 进阶区 刷题记录
    攻防世界 web 新手练习 刷题记录
    TensorFlow01:增加变量显示+tensorboard可视化
    TensorFlow01:梯度下降
    TensorFlow01:张量
    01深度学习介绍
    05Python爬虫:响应内容写入文件
  • 原文地址:https://www.cnblogs.com/xiongqiangcs/p/3801162.html
Copyright © 2011-2022 走看看