📣 独立日限时特惠: VIP通行证立减$68
查看: 1716| 回复: 2
跳转到指定楼层
上一主题 下一主题
收起左侧

[树/链表/图] Lintcode链表一题疑问

全局:

注册一亩三分地论坛,查看更多干货!

您需要 登录 才可以下载或查看附件。没有帐号?注册账号

x
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.

Have you met this question in a real interview? Yes
Example
Given a List  3->2->1->5->null and n = 2, return node  whose value is 1.


九章给的答案是:
public class Solution {
    /**
     * @param head: The first node of linked list.
     * @param n: An integer.
     * @return: Nth to last node of a singly linked list.
     */
    ListNode nthToLast(ListNode head, int n) {
        if (head == null || n < 1) {
            return null;
        }
       
        ListNode p1 = head;
        ListNode p2 = head;
        for (int j = 0; j < n - 1; ++j) {
            if (p2 == null) {
                return null;
            }
            p2 = p2.next;
        }
        while (p2.next != null) {   
            p1 = p1.next;   
            p2 = p2.next;
            }
            return p1;
    }
}
但是在for循环那里好像临界值有bug,比如 3->2->1->5->null and n = 5,依然可以返回3.    实际上n=4才该返回3,n=5该返回null

上一篇:leetcode用python刷可不可以,面试没问题吧
下一篇:Leetcode公司分类2017年1月
🔗
Ajay91 2017-1-9 01:30:11 | 只看该作者
全局:
会出Exception  java.lang.NullPointerException
是不是题目设定不考虑n大于nodes个数的情况
回复

使用道具 举报

🔗
 楼主| KeithWang123 2017-1-9 13:41:23 | 只看该作者
全局:
Ajay91 发表于 2017-1-9 01:30
会出Exception  java.lang.NullPointerException
是不是题目设定不考虑n大于nodes个数的情况

我觉得不是,for里面的if就是判断n大于nodes的,我觉得应该把p = p.next放到if语句前面,这样就ok了,在lintcode上也ac了.
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册账号
隐私提醒:
  • ☑ 禁止发布广告,拉群,贴个人联系方式:找人请去🔗同学同事飞友,拉群请去🔗拉群结伴,广告请去🔗跳蚤市场,和 🔗租房广告|找室友
  • ☑ 论坛内容在发帖 30 分钟内可以编辑,过后则不能删帖。为防止被骚扰甚至人肉,不要公开留微信等联系方式,如有需求请以论坛私信方式发送。
  • ☑ 干货版块可免费使用 🔗超级匿名:面经(美国面经、中国面经、数科面经、PM面经),抖包袱(美国、中国)和录取汇报、定位选校版
  • ☑ 查阅全站 🔗各种匿名方法

本版积分规则

>
快速回复 返回顶部 返回列表