-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRemoveDuplicatesfromSortedListII.java
More file actions
54 lines (49 loc) · 1.25 KB
/
RemoveDuplicatesfromSortedListII.java
File metadata and controls
54 lines (49 loc) · 1.25 KB
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
package com.mirraico.leetcode;
public class RemoveDuplicatesfromSortedListII {
/**
* 不补头部的做法,不好理解
*
public ListNode deleteDuplicates(ListNode head) {
if(head == null || head.next == null) return head;
boolean headFlag = true;
ListNode p = head, q = head;
while(true) {
while(q != null && q.next != null) {
if(q.val != q.next.val) break; //连续的去完为止
while(q.next != null && q.val == q.next.val) q = q.next;
q = q.next;
}
if(headFlag) head = q;
else p.next = q;
if(q == null || q.next == null) break;
p = q; q = q.next;
headFlag = false;
}
return head;
}
*/
public ListNode deleteDuplicates(ListNode head) {
if(head == null || head.next == null) return head;
ListNode fakeHead = new ListNode(0);
fakeHead.next = head;
ListNode p = fakeHead, q = head;
while(true) {
while(q != null && q.next != null) {
if(q.val != q.next.val) break; //连续的去完为止
while(q.next != null && q.val == q.next.val) q = q.next;
q = q.next;
}
p.next = q;
if(q == null) break;
p = p.next; q = q.next;
}
return fakeHead.next;
}
public static void main(String[] args) {
}
}
class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; next = null; }
}