forked from EasonLeeee/TargetOffer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patht57_删除链表中重复的节点.java
64 lines (60 loc) · 1.69 KB
/
t57_删除链表中重复的节点.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
在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。 例如,链表1->2->3->3->4->4->5 处理后为 1->2->5
/**
* 测试用例: 1->1->2->3->3
**/
public class Solution {
public ListNode deleteDuplication(ListNode pHead)
{
if (pHead == null) {
return null;
}
ListNode pre = null;
ListNode cur = pHead;
while (cur != null) {
ListNode next = cur.next;
boolean needDelete = false;
//判读是否删除当前节点
if (next != null && cur.val == next.val)
needDelete = true;
if (!needDelete) {
pre = cur;
cur = next;
} else {
//cur后移,直到为null或指向不重复元素
while (cur.next != null && cur.val == next.val) {
cur = next;
next = cur.next;
}
cur = next;
//更新pre
if (pre == null) {
pHead = cur;
} else {
pre.next = cur;
}
}
}
return pHead;
}
}
//除去重复元素,仅保留一个重复元素版本
public class Solution {
public ListNode deleteDuplication(ListNode pHead)
{
if (pHead == null) {
return null;
}
ListNode cur = pHead;
while (cur.next != null) {
while (cur.next != null) {
if (cur.val == cur.next.val) {
cur.next = cur.next.next;
} else {
break;
}
}
cur = cur.next;
}
return pHead;
}
}