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.

/**
 * 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) 
    {
        //ListNode *dummy=new ListNode(0);
        //dummy->next=head;
        ListNode *dummy=head;
        if(!head) return head;
        while(head)
        {
            while(head->next&&(head->val==head->next->val))
            {
                head->next=head->next->next;
            }
            head=head->next;
        }
        
        return dummy;
    }
};


你可能感兴趣的:(List)