链表倒数第n个节点
找到单链表倒数第n个节点,保证链表中节点的最少数量为n。
样例
给出链表 3->2->1->5->null和n = 2,返回倒数第二个节点的值1.
分析:本题方法是遍历一遍算出有多少个节点,然后减去要求的倒数数字,再次遍历。应该还可以采用下标的办法,即在第一遍遍历的过程中保存在将内容保存在数组中,第二次直接可以靠下标寻找(不过本题不太适用。。。因为要返回的是链表的数据结构而不是只是内容)
/**
* 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 num=0;
ListNode *tmp=head;
while(tmp)
{
num++;
tmp=tmp->next;
}
for(int i=0;i<num-n;i++)
head=head->next;
return head;
}
};
链表倒数第n个节点
Accepted
总耗时:
78 ms
100% 数据通过测试.