Given a linked list, remove the nth node from the end of 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 will always be valid.
同时可以逆向思维 n = length - 要挪动的节点数
/**
* 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) {
ListNode start = new ListNode(0);
ListNode point2 = start, point1 = start;
start.next = head;//这样目前两个指针都指向了同样的节点
for(int i=1; i<=n+1; i++) {
point1 = point1.next;
}
while(point1 != null) {
point2 = point2.next;
point1 = point1.next;
}
point2.next = point2.next.next;
return start.next;
}
}
So brilliant!!