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