LeetCode-19 Remove Nth node from End of List (remove tail nth node)
Given A linked list, remove the nth node from the end of the list and return its head.
For example,
Given linked list:1->2->3->4->5, and n = 2.
After removing the second node from the end, the linked list becomes 1->2->3->5.
Note:
Given n would always be valid.
Try to do the in one pass.
Idea: Set two nodes, one node advance n position, then the other node starts, when the first node in the end, the second node position is the reciprocal n-bit.
My Code:
public class Solution {public
ListNode removenthfromend (listnode head, int n) {
ListNode flag = new ListNode (head . val);
Flag.next = Head.next;
ListNode fir = new ListNode (0);
Fir.next = head;
ListNode sec = new ListNode (0);
Sec.next = head;
for (int i = 0; i < n; i++) {
fir = Fir.next;
}
while (fir.next!=null) {
fir = Fir.next;
SEC = Sec.next;
}
if (sec.next! = null) {
sec.next = sec.next.next;
}
if (Sec.next = = Flag.next) {
return head.next;
} else {
return head;}}
}
The later part of the judgment is based on the situation of the submission error, admire those can be a code without so many cases to solve.
Runtime: 303 ms
Other people's code (more concise than I, run faster):
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode Next;
* ListNode (int x) {val = x;}
* *
/public class Solution {public
ListNode removenthfromend (listnode head, int n) {
if (head = = NULL ) return null;
Final ListNode _head = new ListNode (0);
_head.next = head;
ListNode fast = _head;
ListNode slow = _head;
for (int i = 0; i< n; i++) fast = Fast.next;
while (fast! = NULL && Fast.next! = null) {
fast = Fast.next;
slow = Slow.next;
}
Slow.next = Slow.next.next;
return _head.next;
}
}