码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode:Remove Duplicates from Sorted List

时间:2015-07-16 18:22:09      阅读:87      评论:0      收藏:0      [点我收藏+]

标签:

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

 

LeetCode:Remove Duplicates from Sorted List

标签:

原文地址:http://www.cnblogs.com/xiaoying1245970347/p/4651793.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!