Leetcode Remove Duplicates from Sorted List II

OpenSoucre發表於2014-06-21

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));
}

 

相關文章