Skip to content

Commit 683ad2c

Browse files
committed
remove-nth-node-from-end-of-list
1 parent fd1b11b commit 683ad2c

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
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+
int size = getSizeOfListNode(head);
14+
15+
if (size - n - 1 >= 0) {
16+
ListNode prev = moveNth(head, size - n - 1);
17+
ListNode target = moveNth(head, size - n);
18+
prev.next = target.next;
19+
} else {
20+
head = head.next;
21+
}
22+
23+
24+
return head;
25+
}
26+
public ListNode moveNth(ListNode head, int n){
27+
while (head != null){
28+
if (n == 0) break;
29+
head = head.next;
30+
n--;
31+
}
32+
return head;
33+
}
34+
public void removeNth(ListNode head, int n){
35+
int cnt = n;
36+
37+
}
38+
public int getSizeOfListNode(ListNode head){
39+
int size = 0;
40+
while (head != null) {
41+
size ++;
42+
head = head.next;
43+
}
44+
return size;
45+
}
46+
}
47+
48+

0 commit comments

Comments
 (0)