问题描述:
找到单链表倒数第n个节点,保证链表中节点的最少数量为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.
*/
* @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
if (head== NULL) return NULL;
ListNode *p;
p= head;
int count= 1;
while (p->next!= NULL )
{ p= p->next;
count++;
}
if ((count-n)== 0) {
return head;
}
p= head;
for (int i= 1; i< count-n+1; i++)
{ p= p->next;
}
return p;
}
};
感想: