LeetCode:Remove Duplicates from Sorted List

Problem:

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.

Solution:同Remove Duplicates from Sorted Array的思路一样,每次用结果链表的尾指针pre与遍历原链表的指针last的val作比较,不同则加入原链表。最后返回结果,注意每次加入

结果链表中,pre->next=NULL。

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     ListNode* deleteDuplicates(ListNode* head) {
12         
13         if(head==NULL) return head;
14         ListNode *dummy=new ListNode(-1);
15         
16         ListNode *pre=head;
17         ListNode *last=head->next;
18         
19         dummy->next=pre;
20         pre->next=NULL;
21         
22         while(last!=NULL)
23         {
24             if(pre->val!=last->val)
25             {
26                 pre->next=last;
27                 pre=pre->next;
28                 last=last->next;
29                 pre->next=NULL;
30             }
31             else
32                 last=last->next;
33             
34         }
35         return dummy->next;
36         
37     }
38 };

 

posted @ 2015-07-16 16:51  尾巴草  阅读(118)  评论(0编辑  收藏  举报