š” LeetCode 83 - Remove Duplicates from Sorted List
š” LeetCode 83 - Remove Duplicates from Sorted List
문ģ
GivenĀ theĀ headĀ ofĀ aĀ sortedĀ linkedĀ list,Ā deleteĀ allĀ duplicatesĀ suchĀ thatĀ eachĀ elementĀ appearsĀ onlyĀ once.Ā
ReturnĀ theĀ linkedĀ listĀ sortedĀ asĀ well.
ģ ģ¶ė „ ģģ
ā ģģ 1
1
2
Input: head = [1,1,2]
Output: [1,2]
ā ģģ 2
1
2
Input: head = [1,1,2,3,3]
Output: [1,2,3]
ģ ģ½ģ”°ź±“
- The number of nodes in the list is in the range [0, 300].
-100 <= Node.val <= 100
- TheĀ listĀ isĀ guaranteedĀ toĀ beĀ sortedĀ inĀ ascendingĀ order.
ģģ± ģ½ė
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
/**
* Definition for singly-linked list.
* public class ListNode {
*Ā Ā Ā Ā int val;
*Ā Ā Ā Ā ListNode next;
*Ā Ā Ā Ā ListNode() {}
*Ā Ā Ā Ā ListNode(int val) { this.val = val; }
*Ā Ā Ā Ā ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode deleteDuplicates(ListNode head) {
// 1. ė³ģ ģ ģø ė° ģ“źø°ķ
ListNode resultNode = new ListNode();
ListNode tempNode = resultNode;
// 2. ģ ķØģ± ģ²“ķ¬ 1 : headź° nullģ¼ ź²½ģ°
if (head == null) return null;
// 3. ģ ķØģ± ģ²“ķ¬ 2 : head.nextź° nullģ¼ ź²½ģ°
if (head.next == null) return head;
// 4. ģķķė©° ź²°ź³¼ ė
øė ģģ±
while (head != null && head.next != null) {
if (head.val == head.next.val) {
// ķ ė
øėģ ė¤ģ ė
øė ź°ģ“ ź°ģ ź²½ģ° ė¤ģ ė
øė 걓ėė°źø°
tempNode.next = head.next;
} else {
// ķ ė
øėģ ė¤ģ ė
øė ź°ģ“ ė¤ė„¼ ź²½ģ° ź²°ź³¼ ė
øėģ ģ¶ź° ķ ģ“ė
tempNode.next = head;
tempNode = tempNode.next;
}
// head ģ“ė
head = head.next;
}
// 5. ė°ķ
return resultNode.next;
}
}
This post is licensed under CC BY 4.0 by the author.