博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Leetcode Remove Nth Node From End of List
阅读量:4358 次
发布时间:2019-06-07

本文共 1872 字,大约阅读时间需要 6 分钟。

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.


解题思路:

要想one pass解决,需用fast 和slow 双指针。

首先先让faster从起始点往后跑n步。然后再让slower和faster一起跑,直到faster==null时候,slower所指向的node就是需要删除的节点。

注意,一般链表删除节点时候,需要维护一个prev指针,指向需要删除节点的上一个节点。

为了方便起见,当让slower和faster同时一起跑时,就不让 faster跑到null了,让他停在上一步,faster.next==null时候,这样slower就正好指向要删除节点的上一个节点,充当了prev指针。这样一来,就很容易做删除操作了。

slower.next = slower.next.next(类似于prev.next = prev.next.next)。

同时,这里还要注意对删除头结点的单独处理,要删除头结点时,没办法帮他维护prev节点,所以当发现要删除的是头结点时,直接让head = head.next并returnhead就够了。

Use fast and slow pointers. The fast pointer is n steps ahead of the slow pointer. When the fast reaches the end, the slow pointer points at the previous element of the target element.


 Java code:

/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { val = x; } * } */public class Solution {    public ListNode removeNthFromEnd(ListNode head, int n) {        if(head == null) {            return null;        }        ListNode slow = head, fast = head;         // The fast pointer is n steps ahead of the slow pointer.        for(int i =0;i < n; i++) {            fast = fast.next;        }        //remove the head        if(fast == null) {            head = head.next;            return head;        }        while(fast.next != null) {            fast = fast.next;            slow = slow.next;        }        slow.next = slow.next.next;        return head;    }}

Reference:

1. http://www.programcreek.com/2014/05/leetcode-remove-nth-node-from-end-of-list-java/

2. http://www.cnblogs.com/springfor/p/3862219.html

 

转载于:https://www.cnblogs.com/anne-vista/p/4799747.html

你可能感兴趣的文章
hdu 1506
查看>>
USACO 2.4 Fractions to Decimals
查看>>
nyoj 我排第几个
查看>>
unity3d实现Socket
查看>>
Asp.Net WebService实例
查看>>
联机调试,如何配置局域网内文件服务器
查看>>
last modified -- expires 初步解释
查看>>
事情做完之后的测试
查看>>
svn tree conflicts 解决方法
查看>>
[转]三层架构与MVC之间的区别
查看>>
08、内建函数
查看>>
Glibc 与 libc 的区别和联系
查看>>
hdu 1032 The 3n + 1 problem
查看>>
380. Insert Delete GetRandom O(1)
查看>>
电路相关知识--读<<继电器是如何成为CPU的>>
查看>>
你在职场中值多少钱?
查看>>
angular风格指南
查看>>
Unity UGUI烟雾效果
查看>>
[JavaScript]Promise
查看>>
类型转换(2)
查看>>