【LeetCode】82. Remove Duplicates from Sorted List II

1.题目描述

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

2.Solutions

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public static ListNode deleteDuplicates(ListNode head) {
if(head == null || head.next == null) return head;
ListNode dummy=new ListNode(0);
dummy.next=head;
//双指针
ListNode pre=dummy;
ListNode cur=head;
while(cur!=null){
while(cur.next!=null&&cur.val==cur.next.val){
cur=cur.next;
}
if(pre.next==cur)
pre=pre.next;
else
pre.next=cur.next;

cur=cur.next;
}
return dummy.next;
}
(完)
谢谢你请我吃糖果!
0%