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.
注意的点:当需要被remove的节点是head。(开始写的程序直接只用一个变量记需要被remove的节点的前一个节点,结果就导致在为head时的这种情况处理错误)
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode p1 = head;
ListNode p2 = head;
ListNode removeNode = head;
int i = 0;
while(p1!=null){
p1 = p1.next;
i++;
if(i > n){
p2 = removeNode;
removeNode = removeNode.next;
}
}
if(removeNode == head){
head = head.next;
}else{
p2.next = removeNode.next;
}
return head;
}
}