Skip to content

Commit 542f880

Browse files
committed
Solution Week12:removce-nth-node-from-end-of-list
1 parent 9a676fd commit 542f880

1 file changed

Lines changed: 49 additions & 0 deletions

File tree

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
/*
2+
시간 복잡도: O(N)
3+
공간 복잡도: O(1)
4+
*/
5+
class Solution {
6+
public ListNode removeNthFromEnd(ListNode head, int n) {
7+
ListNode dummy = new ListNode(0);
8+
dummy.next = head;
9+
10+
ListNode fast = dummy;
11+
ListNode slow = dummy;
12+
13+
for (let i = 0; i <= n; i++) {
14+
fast = fast.next;
15+
}
16+
17+
while(fast != null) {
18+
fast = fast.next;
19+
slow = slow.next;
20+
}
21+
22+
slow.next = slow.next.next;
23+
24+
return dummy.next;
25+
}
26+
}
27+
28+
/*
29+
첫 번째 풀이
30+
class Solution {
31+
public ListNode removeNthFromEnd(ListNode head, int n) {
32+
List<ListNode> list = new ArrayList<>();
33+
34+
while(head != null) {
35+
list.add(head);
36+
head = head.next;
37+
}
38+
39+
list.remove(list.size()-n);
40+
if (list.isEmpty()) return null;
41+
42+
for (int i = 0; i < list.size()-1; i++) {
43+
list.get(i).next = list.get(i+1);
44+
}
45+
list.get(list.size()-1).next = null;
46+
return list.get(0);
47+
}
48+
}
49+
*/

0 commit comments

Comments
 (0)