LeetCode82 Remove Duplicates from Sorted List II

Posted wangxiaobao的博客

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode82 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.(Medium)

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

分析:

链表去重的follow-up,但是题号这个在前面,要把有重复元素,则所有该元素均删掉。

注意:

1. 使用dummy node处理头结点被删除掉的情况。

2. 只要有head-> next -> val存在时,先判断head -> next是否为空。

代码:

 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         ListNode dummy(0);
13         dummy.next = head;
14         head = &dummy;
15         while(head -> next != nullptr && head -> next -> next != nullptr) {
16             if (head -> next -> val == head -> next -> next -> val) {
17                 int val = head -> next -> val;
18                 while (head -> next != nullptr && head -> next -> val == val) { //只要取head->next,先判断
19                     ListNode* temp = head -> next;
20                     head -> next = head -> next -> next;
21                     delete temp;
22                 }
23             }
24             else {
25                 head = head -> next;
26             }
27         }
28         return dummy.next;
29     }
30 };

 

 

以上是关于LeetCode82 Remove Duplicates from Sorted List II的主要内容,如果未能解决你的问题,请参考以下文章

leetcode 82 Remove Duplicates from Sorted List II

LeetCode82 Remove Duplicates from Sorted List II

[LeetCode]82. Remove Duplicates from Sorted List II

[LeetCode] 82. Remove Duplicates from Sorted List II

leetcode:82. Remove Duplicates from Sorted List II(Java)解答

一天一道LeetCode#82. Remove Duplicates from Sorted List II