-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDeleteDuplicatesFromListNode.java
More file actions
76 lines (71 loc) · 2.27 KB
/
DeleteDuplicatesFromListNode.java
File metadata and controls
76 lines (71 loc) · 2.27 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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package basic.doublePointer;
import basic.linkedList.ListNode;
public class DeleteDuplicatesFromListNode {
private static DeleteDuplicatesFromListNode deleteDuplicatesFromListNode = new DeleteDuplicatesFromListNode();
public static void main(String[] args) {
ListNode head = ListNode.getListNodes(1,1,1,2,3);
System.out.println(deleteDuplicatesFromListNode.deleteDuplicates2(head).toString());
}
/**
* leetcode82 Remove Duplicates from Sorted List II
* <p>
* 给定一个有序链表,删除所有重复元素,只保留不重复的元素
* <p>
* Example 1:
* <p>
* Input: 1->2->3->3->4->4->5
* Output: 1->2->5
* Example 2:
* <p>
* Input: 1->1->1->2->3
* Output: 2->3
*/
public ListNode deleteDuplicates2(ListNode head) {
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode pre = dummy;
ListNode cur = head;
while (cur != null) {
boolean isDuplicate =false;
//不断删除重复元素,while循环结束时只保留一个元素
while (cur.next!=null && cur.val == cur.next.val) {
cur.next = cur.next.next;
isDuplicate =true;
}
//如果本轮迭代中出现过重复元素,跳过重复元素
if(isDuplicate) {
pre.next=pre.next.next;
}else {
pre=pre.next;
}
cur=pre.next;
}
return dummy.next;
}
/**
* leetcode83. Remove Duplicates from Sorted List
* 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
* @param head
* @return
*/
public ListNode deleteDuplicates(ListNode head) {
if(head==null || head.next==null) return head;
ListNode cur=head;
while (cur!=null) {
while (cur.next!=null && cur.val==cur.next.val) {
cur.next=cur.next.next;
}
cur=cur.next;
}
return head;
}
}