求解单链表第K个节点或者倒数第K个节点总是一个O(n)的问题!一般的求解倒数第K个问题是转换为求解第N-K个节点的问题,这样需要求出链表总长N,实际上可以做的更好!
求解倒数第K个节点更好的一种做法是不求解链表长度,使用一个指针指向第K个节点,另一个指针指向第一个节点,两个指针同步移动,当第一个指针移动到末尾,第二个指针就指向倒数第K个节点!
#include <iostream>
using namespace std;
struct list {
int value;
struct list *next;
};
struct list *insert(struct list *head, int v)
{
if (head) {
head->next = insert(head->next, v);
} else {
head = new struct list;
head->value = v;
head->next = 0;
}
return head;
}
struct list *getrnode(struct list *head, size_t k)
{
struct list *cursor = head;
while (cursor && k--)
cursor = cursor->next;
while (cursor) {
head = head->next;
cursor = cursor->next;
}
return head;
}
int main()
{
struct list *head1 = 0;
head1 = insert(head1, 0);
head1 = insert(head1, 1);
head1 = insert(head1, 2);
head1 = insert(head1, 3);
head1 = insert(head1, 4);
head1 = insert(head1, 5);
head1 = insert(head1, 6);
head1 = insert(head1, 7);
head1 = insert(head1, 8);
head1 = insert(head1, 9);
cout << "node: " << getrnode(head1, 3)->value << endl;
cout << "node: " << getrnode(head1, 7)->value << endl;
return 0;
}