leetcode 82. 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.

Example 1:

Input: 1->2->3->3->4->4->5
Output: 1->2->5

Example 2:

Input: 1->1->1->2->3
Output: 2->3

题目大意:给定已排序的链表,删除所有有重复数字的结点。

c++:

 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 == nullptr) || (head->next == nullptr)) return head; //如果链表为空或者只有一个结点,直接返回
13         ListNode *ans = new ListNode(0); //为方便后续操作,建立头结点
14         ListNode *cur = ans; //cur指针指向结果链表的表尾
15         ListNode *slow = head, *fast;
16         while (slow != nullptr) {
17             fast = slow->next;
18             while (fast != nullptr && (fast->val == slow->val)) //只要fast不为空,并且其值和slow->val相等,那么fast往后移
19                 fast = fast->next;
20             if (slow->next == fast) { //slow指向fast,说明slow和fast相邻且值不相等,那么slow指向的结点可以并入结果链表中
21                 cur->next = slow;
22                 cur = slow;
23                 cur->next = nullptr; //很关键,需要及时将结果链表和slow指向的head链表断开。
24             }
25             slow = fast; //不管前面slow是否指向fast,fast指向的结点都是下一个并入结果链表的候选结点。
26             //cur->next = nullptr;
27         }
28         return ans->next;
29     }
30 };
posted @ 2020-01-14 10:41  琴影  阅读(217)  评论(0编辑  收藏  举报