完整C语言程序查找倒数第k个快慢指针
时间: 2023-12-18 20:03:25 浏览: 35
下面是一个完整的C语言程序,可以实现查找链表中倒数第k个节点的功能。
```c
#include <stdio.h>
#include <stdlib.h>
struct ListNode {
int val;
struct ListNode *next;
};
struct ListNode* findKthToTail(struct ListNode* head, int k) {
if (head == NULL || k <= 0) {
return NULL;
}
struct ListNode *fast = head;
struct ListNode *slow = head;
for (int i = 0; i < k; i++) {
if (fast) {
fast = fast->next;
} else {
return NULL;
}
}
while (fast) {
fast = fast->next;
slow = slow->next;
}
return slow;
}
int main() {
struct ListNode *head = (struct ListNode*)malloc(sizeof(struct ListNode));
head->val = 1;
head->next = NULL;
struct ListNode *p = head;
for (int i = 2; i <= 10; i++) {
struct ListNode *node = (struct ListNode*)malloc(sizeof(struct ListNode));
node->val = i;
node->next = NULL;
p->next = node;
p = node;
}
struct ListNode *res = findKthToTail(head, 3);
if (res) {
printf("倒数第3个节点的值为:%d\n", res->val);
} else {
printf("链表中没有倒数第3个节点\n");
}
return 0;
}
```
在这个程序中,我们首先定义了一个链表,然后调用了findKthToTail函数来查找倒数第k个节点。最后,将倒数第k个节点的值输出到控制台上。
需要注意的是,为了方便起见,这个程序中只是手动创建了一个链表,实际应用中,链表的创建和初始化可能会有很多不同的方式。