您的位置:首页 > Web前端 > Node.js

leetcode - 19. Remove Nth Node From End of List

2018-02-20 17:54 417 查看
Problem: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.解释:移除链表中倒数第n个结点。(给出的n不会大于链表长度)

Solve: 用两个前后指向结点去定位需要移除的结点位置。由于是倒数第n个结点,那么我们构造两个相距距离是n的两个指向结点如:

list:1->2->3->4->5, and n = 2.前指向结点在5的位置,后指向结点在3的位置,然后将指向3的结点的next指向5就行了,这样就移除了倒数第2个结点。
这种情况结束在是 前指针到达末尾 。前后指针相距n,后指针后面是需要移除的结点。(时间复杂度O(n),AC-16ms)public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode res=head;//用于返回头节点
ListNode front=head;//前指向结点
ListNode behind=head;//后指向结点
while (n-->0){
front=front.next;
}
if(front==null){//n为链表长度的情况,就是移除了头结点
return res.next;
}
while (front.next!=null){//前后指向结点进行移动直到前指向结点到达链表末端
front=front.next;
behind=behind.next;
}
if(behind.next!=null){//可能出现移除的是最后一个结点,需要进行非空判断
behind.next=behind.next.next;
}
else {
behind.next=null;
}
return res;
}后记:感觉很多链表题目都会用到前后不同的两个指针进行操作。这个思想还是很重要的。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: