题目:链表中倒数第n个节点
样例:给出链表3->2->1->5->null和n=2,返回倒数第二个节点的值1。
思路:首先排除空链表的情况,然后设定指针p,设定一个计数器count,先计算这个链表的节点数,如果节点数等于所求值n,返回第一个节点,否则,使指针p一直遍历到count-n+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
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;
}
};
感想:这道题较前几道来说有一些麻烦,因为要求倒数第n个节点,所以要先求链表的长度,然后再从正向找到count-n+1的节点,即为所求节点。