Skip to content

Commit 2b22419

Browse files
committed
add remove nth node from end of list solution
1 parent 9acfae1 commit 2b22419

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* public class ListNode {
4+
* int val;
5+
* ListNode next;
6+
* ListNode() {}
7+
* ListNode(int val) { this.val = val; }
8+
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
9+
* }
10+
*/
11+
class Solution {
12+
public ListNode removeNthFromEnd(ListNode head, int n) {
13+
14+
// length 1์ธ ๊ฒฝ์šฐ๋ฅผ ์œ„ํ•ด temp ์ƒ์„ฑ
15+
ListNode temp = new ListNode(0);
16+
temp.next = head;
17+
18+
// ํˆฌ ํฌ์ธํ„ฐ ์„ ์–ธ
19+
ListNode fast = temp;
20+
ListNode slow = temp;
21+
22+
// n + 1์นธ๋งŒํผ fast ๋จผ์ € ์ด๋™
23+
for (int i = 0; i < n + 1; i++) {
24+
fast = fast.next;
25+
}
26+
27+
while (fast != null) {
28+
fast = fast.next;
29+
// ๋Š์–ด์ง€๋Š” ๋…ธ๋“œ ๋ฐ”๋กœ ์•ž๊นŒ์ง€ ์ด๋™
30+
slow = slow.next;
31+
}
32+
33+
// slow.next = ๋Š์–ด์ ธ์„œ ์น˜ํ™˜ํ•ด์•ผ ํ•˜๋Š” ์œ„์น˜
34+
slow.next = slow.next.next;
35+
36+
return temp.next;
37+
}
38+
}
39+

0 commit comments

Comments
ย (0)