输入一个单向链表,输出该链表中倒数第k个结点,链表的最后一个结点是倒数第1个节点。给我包含头文件的完整的代码
时间: 2023-04-08 11:02:43 浏览: 116
链表中倒数第k个结点
抱歉,我可以回答这个问题。以下是包含头文件的完整代码:
#include <stdio.h>
#include <stdlib.h>
typedef struct ListNode {
int val;
struct ListNode *next;
} ListNode;
ListNode* getKthFromEnd(ListNode* head, int k) {
ListNode *fast = head, *slow = head;
for (int i = 0; i < k; i++) {
fast = fast->next;
}
while (fast != NULL) {
fast = fast->next;
slow = slow->next;
}
return slow;
}
int main() {
ListNode *head = (ListNode*)malloc(sizeof(ListNode));
head->val = 1;
head->next = NULL;
ListNode *cur = head;
for (int i = 2; i <= 5; i++) {
ListNode *node = (ListNode*)malloc(sizeof(ListNode));
node->val = i;
node->next = NULL;
cur->next = node;
cur = cur->next;
}
ListNode *res = getKthFromEnd(head, 2);
printf("%d\n", res->val);
return 0;
}
阅读全文