0%

leetCode-82:Remove Duplicates from Sorted List II

问题描述

给定一个有序链表,要求将链表中的所有重复节点(包括自己)全部删除。题目链接:**点我**

样例输入输出

输入:1->2->2->2->3

输出:1->3

输入:1->1->1->2

输出:2

问题解法

此题比较简单,直接遍历判断删除即可。代码如下

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

if (p.next != next)
{
p.next = next.next;
}
else
{
p = p.next;
}
}

return dummy.next;
}
}