找到單鏈表倒數第n個節點,保證鏈表中節點的最少數量為n。
您在真實的面試中是否遇到過這個題?
Yes
樣例
給出鏈表 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
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;
}
};