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.
思路:
1.删除节点需要两个指针,指向待删除节点和他的前驱;
2.找到倒数第n个节点,需要两个指针,二者相隔n-1个指针;
3.二者结合需要3个指针,待删除节点和他的前驱,指示结尾的节点(用来确定倒数第n);
4 删除一个节点的操作,他的前驱指向该节点后继,当前节点指向空
public ListNode removeNthFromEnd(ListNode head, int n) {
if(head==null) return head; //安全检查
ListNode pre=new ListNode(-1);
pre.next=head; //删除元素必备指针
ListNode res=pre; //结果相关的指针
ListNode p=head; //后指针
for(int i=0;i<n-1;i++){
p=p.next;
}
ListNode s=head; //前指针
while(p!=null&&p.next!=null){ //后指针到达链表的结尾,s指针到达待删除的节点,pre为s的前驱
p=p.next;
s=s.next;
pre=pre.next;
}
pre.next=s.next; //删除节点的要求
s.next=null;
return res.next;
}