【Leetcode】【Medium】Remove Duplicates from Sorted List II

Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.

For example,
Given 1->2->3->3->4->4->5, return 1->2->5.
Given 1->1->1->2->3, return 2->3.

 

解题思路1:

拿到题先思考,别急着写代码。什么样的情况能判定此node不是重复的:

1、node在list第一个,并且和后一个结点值不相等;

2、连续三个结点值都不相等,那么中间那个node就可判定为非重复的;

3、最后一个node如果和倒数第二个结点的值不相等,那么此node也是有效结点。

有了上面的分析,模拟思维的过程,就能得到code1:

(注意新链表添加完成后,要将最后一个结点指向空。)

 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         if (!head || !head->next)
13             return head;
14         ListNode *newhead = new ListNode(0);
15         ListNode *newlist = newhead;
16         ListNode* ctrl = head;
17         
18         if (ctrl->val != ctrl->next->val) {
19             newlist->next = ctrl;
20             newlist = newlist->next;
21         }
22         
23         while (ctrl->next) {
24             if ((ctrl->val != ctrl->next->val) && 
25                 (!ctrl->next->next || ctrl->next->val != ctrl->next->next->val)) {
26                 newlist->next = ctrl->next;
27                 newlist = newlist->next;
28             }
29             ctrl = ctrl->next;
30         }
31         
32         newlist->next = NULL;
33         return newhead->next;
34     }
35 };

 

解题思路2:

上面的思路相当于每次移动一个结点作为目标结点,然后判断其与左右两边结点的值是否相同;

每次移动一位,判断2次。如果遇到连续多个重复结点,那么效率就会低。

因此,遍历链表结点:

1、先记录第一个结点node_o;

2、找到前后值不一样的结点node1、node2;

3、如果node_o和node1不相同,说明node1不存在重复,那么node1是有效结点;

   如果不同,说明node1和前面结点重复,那么重新将node2作为起始结点,继续重复1步骤。

代码:

 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         if (!head || !head->next)
13             return head;
14         ListNode *newhead = new ListNode(0);
15         ListNode *newlist = newhead;
16         newlist->next = head;
17         ListNode* ctrl = head;
18         
19         while (ctrl) {
20             while (ctrl->next && ctrl->val == ctrl->next->val)
21                 ctrl = ctrl->next;
22                 
23             if (newlist->next == ctrl)
24                 newlist = newlist->next;
25             else
26                 newlist->next = ctrl->next;
27             ctrl = ctrl->next;
28         }
29         
30         return newhead->next;
31     }
32 };

 

posted @ 2015-05-19 07:36  胡潇  阅读(176)  评论(0编辑  收藏  举报