-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathDeleteDuplication.java
74 lines (68 loc) · 1.94 KB
/
DeleteDuplication.java
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package offer.problem18;
import java.util.List;
/**
* Created with IntelliJ IDEA
*
* @Author yuanhaoyue swithaoy@gmail.com
* @Description p122 18.2 删除链表中重复节点
* @Date 2018-12-02
* @Time 14:48
*/
public class DeleteDuplication {
/**
* 迭代
*/
public static ListNode deleteDuplication(ListNode pHead) {
if(pHead == null || pHead.next != null) {
return pHead;
}
ListNode head = new ListNode(0);
head.next = pHead;
ListNode pre = head;
while(pHead != null && pHead.next != null) {
if(pHead.next.val == pHead.val) {
while(pHead.next != null && pHead.next.val == pHead.val) {
pHead = pHead.next;
}
pre.next = pHead.next;
} else {
pre = pre.next;
}
pHead = pHead.next;
}
return head.next;
}
/**
* 递归
*/
public static ListNode deleteDuplication2(ListNode pHead) {
if(pHead == null || pHead.next == null) {
return pHead;
}
if(pHead.next.val == pHead.val) {
while(pHead.next != null && pHead.next.val == pHead.val) {
pHead = pHead.next;
}
return deleteDuplication(pHead.next);
} else {
pHead.next = deleteDuplication(pHead.next);
return pHead;
}
}
public static class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
public static void main(String[] args) {
ListNode listNode = new ListNode(2);
listNode.next = new ListNode(3);
listNode.next.next = new ListNode(4);
listNode.next.next.next = new ListNode(5);
listNode.next.next.next.next = new ListNode(6);
System.out.println(deleteDuplication(listNode));
System.out.println(1);
}
}