Skip to content

Commit 38d5d35

Browse files
committed
#248 Remove Nth Node From End of List
1 parent e0f07fe commit 38d5d35

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
/*
2+
# Time Complexity: O(n)
3+
# Space Complexity: O(1)
4+
*/
5+
6+
/**
7+
* Definition for singly-linked list.
8+
* public class ListNode {
9+
* int val;
10+
* ListNode next;
11+
* ListNode() {}
12+
* ListNode(int val) { this.val = val; }
13+
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
14+
* }
15+
*/
16+
class Solution {
17+
public ListNode removeNthFromEnd(ListNode head, int n) {
18+
ListNode curr = head;
19+
int cnt = 0;
20+
while (curr != null) {
21+
cnt++;
22+
curr = curr.next;
23+
}
24+
25+
if (cnt == n) { // 예외 처리
26+
return head.next;
27+
}
28+
29+
ListNode prev = null;
30+
curr = head;
31+
for (int i = 0; i < cnt - n; i++, prev = curr, curr = curr.next);
32+
prev.next = curr.next; // 뒤에서 n번째 노드 제거
33+
34+
return head;
35+
}
36+
}

0 commit comments

Comments
 (0)