알고리즘/알고리즘 문제 복기
LeetCode - 19. Remove Nth Node From End of List
내일도무사히
2021. 3. 17. 21:08
leetcode.com/problems/remove-nth-node-from-end-of-list/
Remove Nth Node From End of List - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
Q.
Answer.
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
|
/**
* 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 removeNthFromEnd(ListNode head, int n) {
ListNode dummy = head;
ListNode prev = null;
int length = 0;
// get length;
while(dummy != null) {
++length;
dummy = dummy.next;
}
dummy = head;
int count = 0;
int target_node_prev_no = length - n;
ListNode target_node_prev = head;
if(length == 1) {
head = null;
return head;
}
if(length == 2) {
if(n == 1) {
head.next = null;
}
if(n == 2) {
head = head.next;
}
return head;
}
while(dummy != null) {
++count;
if(target_node_prev_no == 0 && count == 1) {
return head.next;
}
if(dummy.next == null && n == 1) {
target_node_prev.next = null;
break;
}
else {
if(count == target_node_prev_no)
target_node_prev = dummy;
if(count == target_node_prev_no + 2)
target_node_prev.next = dummy;
}
dummy = dummy.next;
}
return head;
}
}
|
cs |
if구문을 참 많이 쓴 것 같다.
풀면서 생각한건 다음과 같이
prev를 체크하는 포인터를 이용해 다다음 노드로 연결하면 간단하게 풀 수 있을 것 같았다.
그런데 n이 노드의 길이와 같을 때와(노드의 맨 처음을 지워야 할 때), 노드의 맨 마지막을 지워야 할 때 에러가 각각 발생해서 if문을 통해 처리해주었는데 코드가 지저분해졌다.
다음과 같이 풀 수도 있다.