File tree Expand file tree Collapse file tree 1 file changed +46
-0
lines changed Expand file tree Collapse file tree 1 file changed +46
-0
lines changed Original file line number Diff line number Diff line change
1
+ // https://leetcode.com/problems/remove-nth-node-from-end-of-list/
2
+
3
+ /**
4
+ * Definition for singly-linked list.
5
+ * public class ListNode {
6
+ * int val;
7
+ * ListNode next;
8
+ * ListNode() {}
9
+ * ListNode(int val) { this.val = val; }
10
+ * ListNode(int val, ListNode next) { this.val = val; this.next = next; }
11
+ * }
12
+ */
13
+
14
+ class Solution {
15
+ public ListNode removeNthFromEnd (ListNode head , int n ) {
16
+
17
+ // If head is empty or by itself, return null
18
+ if (head == null || head .next == null ) {
19
+ return null ;
20
+ }
21
+
22
+ // Create a dummy node to help return value
23
+ ListNode dummy = new ListNode ();
24
+ dummy .next = head ;
25
+
26
+ // Create a left and right node pointer
27
+ ListNode leftNode = dummy ;
28
+ ListNode rightNode = head ;
29
+
30
+ // Move rightNode n steps
31
+ for (int i = 0 ; i < n ; i ++) {
32
+ rightNode = rightNode .next ;
33
+ }
34
+
35
+ // Iterate linked list until rightNode reaches end of list
36
+ while (rightNode != null ) {
37
+ leftNode = leftNode .next ;
38
+ rightNode = rightNode .next ;
39
+ }
40
+
41
+ // Cut target node from linked list
42
+ leftNode .next = leftNode .next .next ;
43
+
44
+ return dummy .next ;
45
+ }
46
+ }
You can’t perform that action at this time.
0 commit comments