描述
找到单链表倒数第n个节点,保证链表中节点的最少数量为n。
样例
给出链表 3->2->1->5->null和n = 2,返回倒数第二个节点的值1.
思考
- 样例返回的是结点值, 而函数要求返回的是结点
代码
// By Lentitude
/**
* 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
// 保证 numberOfHead >= n
int num = 0;
ListNode *front = head;
// 计算总数
while (front != NULL){
num++;
front = front->next;
}
// 从前往后找到该节点
front = head;
int index = 0;
while (front != NULL){
index++;
if (index == num - n + 1){
return front;
}
front = front->next;
}
}
};