【leetcode】83. remove duplicates from sorted list

1.题目描述

Given a sorted linked list, delete all duplicates such that each element appear only once.

给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。

Example 1:

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

Example 2:

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

2.Solutions

类似于82题解决思路:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public static ListNode (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;
pre=pre.next;
}

cur=cur.next;
}
return dummy.next;
}

单指针:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public static ListNode (ListNode head) {
if(head == null || head.next == null)
return head;
ListNode cur = head;
while(cur.next != null){
if(cur.next == null)
break;

if(cur.val == cur.next.val)
cur.next = cur.next.next;
else
cur = cur.next;
}
return head;
}

递归:

1
2
3
4
5
public ListNode (ListNode head) {
if(head == null || head.next == null)return head;
head.next = deleteDuplicates(head.next);
return head.val == head.next.val ? head.next : head;
}

(完)