思路
先求链表的长度
算出待求节点正序位置
再次遍历求值
/**
* 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;
}
};