Remove Nth Node From End of List 删除链表的倒数第 N 个结点
Given the head
of a linked list, remove the nth
node from the end of the list and return its head.
输入:head = [1,2,3,4,5], n = 2
输出:[1,2,3,5]
双指针+虚头
由于要删除倒数第N个节点,原则上要找到倒数第N+1节点。但是这样处理就会超过一次遍历。
一次遍历搞定:
设置p,q 两个指针,p指向虚头,q指向head头结点,q向后走N个节点。如果q不为空的话,此时p,q同时移动,直到q指向null,此时p指向的节点就是那个需要被删除的节点。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode ret = new ListNode(0,head),p = ret,q=head;
int k =n;
while(k>0){
q=q.next;
k--;
}
while(q!=null){
q= q.next;
p=p.next;
}
ListNode tmp = p;
p.next = p.next.next;
return ret.next;
}
}