问题:求一个未知长度的单向链表的倒数第k个节点。
转载还望注明出处:https://blog.csdn.net/AEsun/article/details/90028147
已知算法:有两个指针都指向头指针,第一个指针先走k步,然后第二个指针跟随第一个指针移动,直到第一个指针到达链表结尾,则第二个指针的位置为倒数第k个节点。
时间复杂度分析:第一个指针寻址(first_pointer->next)一共有n次,第二个指针寻址(second_pointer->next)一共 n-k 次,两个指针寻址总和为 2n-k 次。
我的优化能将寻址次数降到 n+k 次,当n足够大时,k为一个常数,则降低了一半的时间。接下来,介绍我的优化算法。
step1:有三个指针,probe(探针),fixed(固定桩),answer(答案),这三个指针首先都指向头指针。
step2:让probe先往前寻址k步,到达第一个k段固定点,然后将fixed固定到probe指针处,此时answer和fixed保持k个节点的距离,probe处于fixed的位置。
step3:接下来是一个迭代过程,假设链表比较长,probe一直负责往前探索,probe每往前探索k个节点,answer移动到fixed桩(answer指向fixed),fixed桩向前移动到probe探针位置(fixed指向probe),目的是让answer和fixed始终保持k个节点的距离。
step4:probe探针在向前探索时,未到k步时即到达链表结尾,此时记录下probe向前探索的步数 i 步,将answer同样向前移动 i 步即到达倒数第k个节点。
通过图片来理解一下具体的过程:
时间复杂度分析:probe指针寻址n次,answer和fixed的都是通过赋值完成,无需寻址,answer需要多走最后的 i 步寻址,由于 i<k ,寻址次数至多为n+k次。但此算法需要增加一个计数器,控制k次循环的前进。
下面时代码实现:
#include<stdio.h>
#include<stdlib.h>
typedef struct Node
{
int value;
struct Node* next;
}Node;
Node* find_kth_end(Node* head, int k)
{
Node* probe = head; //The front pointer, called probe pointer.
Node* fixed = head; //The middle pointer, called fixed pointer.
Node* answer = head; //The behind pointer, finally it will be the answer pointer.
//This step assure the list is longer than k.
for (int i = 0; i < k; i++)
{
//If the list is shorter than k, return the NULL.
if (probe == NULL)
return NULL;
probe = probe->next;
}
//Fixed pointer move to probe pointer.
fixed = probe;
while (1)
{
//The three pointers is k nodes' space each other. Then move forward iteratively.
for (int i = 0; i < k; i++)
{
probe = probe->next;
//If probe pointer arrives the end.
if (probe == NULL)
{
//Now, the i's value is the offset, we need answer pointer to move the answer location.
for (int j = 0; j <= i; j++)
{
answer = answer->next;
}
return answer;
}
}
//The two pointers move forward, then it's a sub-question, we can solve it iteratively.
answer = fixed;
fixed = probe;
}
return NULL;
}
Node* create_list(int n)
{
Node* head = NULL;
Node* current, *future;
int value = 0;
head = (Node*)malloc(sizeof(Node));
head->value = value++;
current = head;
for (int i = 0; i < n-1; i++)
{
future = (Node*)malloc(sizeof(Node));
future->value = value++;
current->next = future;
current = future;
}
current->next = NULL;
return head;
}
int main()
{
int n = 30; //It's for testing, n is the length of list.
Node* head, *result;
head = create_list(30);
result = find_kth_end(head, 7);
printf("%d", result->value);
return 0;
}