找到单链表倒数第n个节点,保证链表中节点的最少数量为n。
样例
给出链表 3->2->1->5->null和n = 2,返回倒数第二个节点的值1.
水题一枚,直接遍历即可。
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 sum=0;
ListNode *r;
r=head;
while(r!=NULL)
{
sum++;
r=r->next;
}
sum=sum-n+1;
r=head;
while(sum>1)
{
r=r->next;
sum--;
}
return r;
}
};