LintCode 166.链表倒数第n个节点

本文介绍了一种高效算法,用于查找链表中倒数第N个节点的方法。通过两次遍历链表,首先确定链表的总长度,然后计算目标节点的正序位置,最后再次遍历链表直至找到目标节点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述

思路
先求链表的长度
算出待求节点正序位置
再次遍历求值

/**
 * Definition of ListNode
 * class ListNode {
 * public:
 *     int val;
 *     ListNode *next;
 *     ListNode(int val) {
 *         this->val = val;
 *         this->next = NULL;
 *     }
 * }
 */


class Solution {
public:
    /*
     * @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) {
        // write your code here
        
        int numNode = 0;
        ListNode *p = head;
        while(p != NULL)
        {
            numNode++;
            p = p->next;
        }
        
        p = head;
        int numInsert = numNode - n + 1;
        while(--numInsert)
        {
            p = p->next;
        }
        return p;
    }
};

参考答案

/**
* 本参考程序来自九章算法,由 @九章算法 提供。版权所有,转发请注明出处。
* - 九章算法致力于帮助更多中国人找到好的工作,教师团队均来自硅谷和国内的一线大公司在职工程师。
* - 现有的面试培训课程包括:九章算法班,系统设计班,算法强化班,Java入门与基础算法班,Android 项目实战班,
* - Big Data 项目实战班,算法面试高频题班, 动态规划专题班
* - 更多详情请见官方网站:http://www.jiuzhang.com/?source=code
*/ 

/**
 * Definition of ListNode
 * class ListNode {
 * public:
 *     int val;
 *     ListNode *next;
 *     ListNode(int val) {
 *         this->val = val;
 *         this->next = NULL;
 *     }
 * }
 */
class Solution {
public:
    /**
     * @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;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值