Post

šŸ’” 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.