Skip to content

Commit ec01f2c

Browse files
removeNthFromEnd
1 parent 4fa44f0 commit ec01f2c

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
import java.util.LinkedList;
2+
3+
// Definition for singly-linked list.
4+
class ListNode {
5+
int val;
6+
ListNode next;
7+
ListNode() {}
8+
ListNode(int val) { this.val = val; }
9+
ListNode(int val, ListNode next) { this.val = val; this.next = next; }
10+
}
11+
12+
class Solution {
13+
14+
public static void main(String[] args) {
15+
Solution s = new Solution();
16+
var node = new ListNode(1, new ListNode(2));
17+
s.removeNthFromEnd(node, 1);
18+
}
19+
20+
public ListNode removeNthFromEnd(ListNode head, int n) {
21+
// 문제: 링크드리스트의 head가 주어지면 끝에서 N번째 노드를 삭제한 결과를 반환하라
22+
// 풀이: n번째만큼 first 이동, 그 후 second를 1칸씩 함께 이동 시킨다 first가 끝에 도달할 때 까지
23+
// 전체 길이 L, 주어진 N이 있을때 이렇게 하면 L - N - 1 위치를 구할 수 있다.
24+
// TC: O(N)
25+
// SC: O(1)
26+
var dummy = new ListNode(-1, head);
27+
var first = head;
28+
for (int i=0; i<n; i++) {
29+
first = first.next;
30+
}
31+
32+
var second = dummy;
33+
34+
while(first != null) {
35+
first = first.next;
36+
second = second.next;
37+
}
38+
39+
second.next = second.next.next;
40+
return dummy.next;
41+
}
42+
43+
}

0 commit comments

Comments
 (0)