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.

 

Hide Tags
 Linked List
 
 
思路:双指针,一个指向要处理的node,一个指向处理完的node,比较两个node的val是否相等,注意,不相等是要将处理完的node->next = NULL,破坏原来的link关系。
 
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
    public:
        ListNode *deleteDuplicates(ListNode *head) {
            if(head == NULL)
                return NULL;

            ListNode dummy(-1);
            dummy.next = head;
            ListNode * p = head;
            p = p->next;

            while(p)
            {
                #if 0
                cout << "p->val\t" << p->val << endl;
                cout << "head->val\t" << head->val << endl;
                #endif
                if(p->val != head->val)
                {   
                    head->next = p;
                    head = p;
                }   
                p = p->next;
                // to break old link
                head->next = NULL;
            }   
            return dummy.next;
        }   
};

 

posted @ 2015-03-17 17:23  穆穆兔兔  阅读(133)  评论(0编辑  收藏  举报