Remove Duplicates from Sorted List

目录

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

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

1
2
3
4
5
6
站在当前节点的角度,设置其next。
next存在
判断next是否重复
重复(当前next设置为next的next(即移除重复),循环判断新next值是否满足条件)
不重复(next不变,判断next的next是否满足条件)
不存在(返回null)
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
38
39
40
41
42
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode deleteDuplicates(ListNode head) {
List l = new ArrayList();
if(head==null){
return null;
}
l.add(head.val);
head.next=ge(head,l);
return head;
}

public ListNode ge(ListNode ln,List l){
if(ln.next == null){
return null;
}
if(l.contains(ln.next.val)){
if(ln.next.next==null){
ln.next = null;
return null;
}else{
ln.next = ln.next.next;
ln.next=ge(ln,l);
}
return ln.next;
}else{
l.add(ln.next.val);
ln.next.next=ge(ln.next,l);
return ln.next;
}
}
}