Leetcode Remove Duplicates from Sorted List

Given a sorted linked list, delete all duplicates such that each element appear only once.

For example,
Given 1->1->2, return 1->2.
Given 1->1->2->3->3, return 1->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 *p = head->next,  *pre = head;
    while(p){
        if(pre->val == p->val){
            ListNode *tmp = p->next;
            pre->next = p->next;
            delete p;
            p = tmp;
        }else{
            pre = p;
            p = p->next;
        }
    }
    return head;
}

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;
    printList(deleteDuplicates(head));
}

 

posted @ 2014-06-21 16:34  OpenSoucre  阅读(135)  评论(0编辑  收藏  举报