资讯专栏INFORMATION COLUMN

[LintCode/LeetCode] Nth to Last Node in List

Salamander / 2084人阅读

摘要:依然是一道找倒数第个结点的链表题,用双指针做。先走,然后和一起走,直到为,的位置就是倒数第个位置。

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 and n = 2, return node whose value is 1.

Note

依然是一道找倒数第n个结点的链表题,用双指针做。fast先走n,然后fast和slow一起走,直到fast为null,slow的位置就是倒数第n个位置。

Solution
public class Solution {
    ListNode nthToLast(ListNode head, int n) {
        ListNode fast = head, slow = head;
        int i = n;
        while (i-- > 0) fast = fast.next;
        while (fast != null) {
            fast = fast.next;
            slow = slow.next;
        }
        return slow;
    }
}

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

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

相关文章

  • [LintCode/LeetCode] LRU Cache

    摘要:方法继承了的很多方法,本身的方法有对运行速度影响不大,随意设定是默认值,为浮点数为,与意思相同最近过的 Problem Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and set. ge...

    walterrwu 评论0 收藏0
  • [LintCode/LeetCode] Super Ugly Number

    摘要:建两个新数组,一个存数,一个存。数组中所有元素初值都是。实现的过程是,一个循环里包含两个子循环。两个子循环的作用分别是,遍历数组与相乘找到最小乘积存入再遍历一次数组与的乘积,结果与相同的,就将加,即跳过这个结果相同结果只存一次。 Problem Write a program to find the nth super ugly number. Super ugly numbers a...

    wuyumin 评论0 收藏0
  • [LintCode/LeetCode] Copy List with Random Pointer

    摘要:大体意思就是,先复制到,顺便将所有的放在再复制所有的到,顺便将所有的放在最后令,令,将和分离,返回的头结点 Problem A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null. ...

    Jacendfeng 评论0 收藏0
  • [LintCode/LeetCode] Jump Game I & II

    摘要:建立动规数组,表示从起点处到达该点的可能性。循环结束后,数组对所有点作为终点的可能性都进行了赋值。和的不同在于找到最少的步数。此时的一定是满足条件的最小的,所以一定是最优解。 Jump Game Problem Given an array of non-negative integers, you are initially positioned at the first index...

    rose 评论0 收藏0
  • [LintCode/LeetCode] Clone Graph [BFS/DFS]

    摘要:开始看这道题目的时候,没有看懂和的作用。然后对这个放入的结点开始操作遍历的所有,当前遍历到的的叫做。当完成,则中没有新的结点了,退出循环。返回在中更新过的,结束。 Problem Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors. We use #...

    fredshare 评论0 收藏0

发表评论

0条评论

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