leetcode-19. Remove Nth Node From End of List
题目:
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.
Try to do this in one pass.
这题的要求是一趟算法。这个稍微麻烦点。主要的思路就是类似两点法,先移动end指针n个节点,在同时移动pre和end两个节点。直到end节点到达终点。。
另外还有需要注意的一点是如果移除的是头节点的话,需要做一些特殊的处理。可以利用end节点自身正好是null这一特性可以使得程序更加简洁。
/**
* 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 pre = head,end = head;
int c = 0;
while(c++ != n && end != null) end = end.next;
if(end == null) return head.next;
while(end.next != null){
pre = pre.next;
end = end.next;
}
pre.next = pre.next.next;
return head;
}
}