资讯专栏INFORMATION COLUMN

[Lintcode] Nth to Last Node in List 链表倒数第N个节点

CoXie / 2473人阅读

摘要:递归法复杂度时间空间思路当递归到链表尾部时返回,每次返回时长度加,一旦长度为时记录下该节点。双指针法复杂度时间空间思路用两个指针,快指针先走步,然后快慢指针同时开始走,保持的距离,这样当快指针到达末尾时,慢指针就是倒数第个。

Nth to Last Node in List

Find the nth to last element of a singly linked list.

The minimum number of nodes in list is n.

递归法 复杂度

时间 O(N) 空间 O(N)

思路

当递归到链表尾部时返回,每次返回时长度加1,一旦长度为N时记录下该节点。

双指针法 复杂度

时间 O(N) 空间 O(1)

思路

用两个指针,快指针先走N步,然后快慢指针同时开始走,保持N的距离,这样当快指针到达末尾时,慢指针就是倒数第N个。

代码
public class Solution {
    ListNode nthToLast(ListNode head, int n) {
        // write your code here
        ListNode slow = head;
        ListNode fast = head;
        while(n-- > 0){
            fast = fast.next;
        }
        while(fast != null){
            fast = fast.next;
            slow = slow.next;
        }
        return slow;
    }
}

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/64520.html

相关文章

  • [LintCode/LeetCode] Nth to Last Node in List

    摘要:依然是一道找倒数第个结点的链表题,用双指针做。先走,然后和一起走,直到为,的位置就是倒数第个位置。 Problem Find the nth to last element of a singly linked list. The minimum number of nodes in list is n. Example Given a List 3->2->1->5->null ...

    Salamander 评论0 收藏0
  • [LeetCode/LintCode] Remove Nth Node From End of L

    Problem Given a linked list, remove the nth node from the end of list and return its head. Example Given linked list: 1->2->3->4->5->null, and n = 2. After removing the second node from the end, the l...

    Jaden 评论0 收藏0
  • LeetCode 19:删除链表倒数N节点 Remove Nth Node From End

    摘要:给定一个链表,删除链表的倒数第个节点,并且返回链表的头结点。示例给定一个链表和当删除了倒数第二个节点后,链表变为说明给定的保证是有效的。值得注意的的是,指向应当删除的节点并无法删除它,应当指向该删除节点的前一个节点。 给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。 Given a linked list, remove the n-th node from the ...

    qiangdada 评论0 收藏0
  • LeetCode 19:删除链表倒数N节点 Remove Nth Node From End

    摘要:给定一个链表,删除链表的倒数第个节点,并且返回链表的头结点。示例给定一个链表和当删除了倒数第二个节点后,链表变为说明给定的保证是有效的。值得注意的的是,指向应当删除的节点并无法删除它,应当指向该删除节点的前一个节点。 给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。 Given a linked list, remove the n-th node from the ...

    周国辉 评论0 收藏0
  • leetcode19 Remove Nth Node From End of List链表中移除

    摘要:虽然时间复杂度还是但是显然我们可以再一次遍历中完成这个任务。现在跳出下标的思路,从另一个角度分析。快慢节点之间的距离始终是。当快节点到达终点时,此时的慢节点就是所要删去的节点。 题目要求 Given a linked list, remove the nth node from the end of list and return its head. For example, ...

    YPHP 评论0 收藏0

发表评论

0条评论

CoXie

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<