题目描述:找到单链表倒数第n个节点,保证链表中节点的最少数量为n。
样例:给出链表 3->2->1->5->null和n = 2,返回倒数第二个节点的值1.
解题思路:定义两个指针p和q指向头部,p先走N个节点,q不动。然后p走一步,q也走一步,等到p走到终点时,q就恰好指向倒数第n。
/**
* 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) {
ListNode*p=head;
ListNode*q=head;
while(n>0&&p!=NULL)
{
q=q->next;
n–;
}
while(q!=NULL)
{
q=q->next;
p=p->next;
}
return p;// write your code here
}
};