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.
Subscribe to see which companies asked this question
/*
*删除链表的倒数第n个元素
*开始感觉先统计有多少个,然后再计算出倒数第n个是正数第多少个。
*但是!
*题目说 one pass。。。
*那么,这样,用两个指针。p,q
*p先跑n步,然后q和p一起跑,那么p跑到最后,q就正好在倒数第n个上面了。。。
*做了这么多单链表的题了,我一前有个很不好的习惯,就是链表头步知道怎么处理,一般都是单独处理T_T
*这一次的难点也是在n等于表长时如何处理头部上,摸索好久,还是不会,只能看大神的代码了,原来是:head=head.next;
*/
public class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
//首先q先行,行n步,这样q走到末尾的时候,p恰好到达n的前一个结点处
ListNode p=head;
ListNode q=head;
for(int i=0;i<n;i++){ //先计算链表长度(刚好移动n个结点)
q=q.next; //像后移动
} //此时q已到达n处
//n等于表长时,有异常产生,必须要单独处理(这个地方还是看了大神的写法,原谅小白真心不会)
if(q == null)
{
head = head.next;
p = null;
return head;
}
while(q.next!=null){
p=p.next;
q=q.next;
} //此时q已到达末尾处,p已到达距末尾结点n个结点的位置
p.next=p.next.next; //删除倒数第n个结点
return head;
}
}
}