找到單鏈表倒數(shù)第n個節(jié)點(diǎn),保證鏈表中節(jié)點(diǎn)的最少數(shù)量為n。
您在真實(shí)的面試中是否遇到過這個題?
Yes
樣例
給出鏈表 3->2->1->5->null和n = 2,返回倒數(shù)第二個節(jié)點(diǎn)的值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
ListNode *p=head;
ListNode *q=head;
for(int i=0;i<n;i++){
p=p->next;
}
while(p!=NULL){
p=p->next;
q=q->next;
}
return q;
}
};