File tree Expand file tree Collapse file tree
remove-nth-node-from-end-of-list Expand file tree Collapse file tree Original file line number Diff line number Diff line change 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+ */
You can’t perform that action at this time.
0 commit comments