-
Notifications
You must be signed in to change notification settings - Fork 0
/
LeetCode_83_DeleteDuplicates.java
79 lines (71 loc) · 2.02 KB
/
LeetCode_83_DeleteDuplicates.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
75
76
77
78
79
package problems.linkedlist;
import problems.common.util.ListNode;
/**
* 83. 删除排序链表中的重复元素
* 难度:简单
* <p>
* 给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。
* <p>
* 示例 1:
* <p>
* 输入: 1->1->2
* 输出: 1->2
* 示例 2:
* <p>
* 输入: 1->1->2->3->3
* 输出: 1->2->3
*
* @author kyan
* @date 2020/1/15
*/
public class LeetCode_83_DeleteDuplicates {
/**
* 自己实现的实在是太蠢了!!!
*/
public static class Solution1 {
public ListNode deleteDuplicates(ListNode head) {
if (head == null || head.next == null) return head;
ListNode slow = head;
ListNode fast = head.next;
while (slow != null && slow.next != null) {
while (fast != null && slow.val == fast.val) {
slow.next = fast.next;
fast.next = null;
fast = slow.next;
}
slow = slow.next;
if (fast != null) {
fast = fast.next;
}
}
return head;
}
}
/**
* 精简版
*/
public static class Solution2 {
public ListNode deleteDuplicates(ListNode head) {
ListNode cur = head;
while (cur != null && cur.next != null) {
if (cur.val == cur.next.val) {
cur.next = cur.next.next;
} else {
cur = cur.next;
}
}
return head;
}
}
public static void main(String[] args) {
//1->1->2->2->3
ListNode head = new ListNode(1);
head.next = new ListNode(1);
head.next.next = new ListNode(2);
head.next.next.next = new ListNode(2);
head.next.next.next.next = new ListNode(3);
Solution1 solution1 = new Solution1();
System.out.println(solution1.deleteDuplicates(head));
//should print 1->2->3
}
}