用C言语实现输入一个单向链表,输出该链表中倒数第k个结点,链表的倒数第1个结点为链表的尾指针。
时间: 2023-08-31 13:12:52 浏览: 31
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node *next;
} Node;
Node *createList() {
Node *head = (Node*)malloc(sizeof(Node));
head->next = NULL;
Node *tail = head;
int x;
while (scanf("%d", &x) != EOF) {
Node *newNode = (Node*)malloc(sizeof(Node));
newNode->data = x;
newNode->next = NULL;
tail->next = newNode;
tail = newNode;
}
return head;
}
void printList(Node *head) {
Node *p = head->next;
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
Node *findKthFromEnd(Node *head, int k) {
Node *fast = head->next;
Node *slow = head->next;
while (fast != NULL && k > 0) {
fast = fast->next;
k--;
}
if (k > 0) {
return NULL;
}
while (fast != NULL) {
fast = fast->next;
slow = slow->next;
}
return slow;
}
int main() {
Node *head = createList();
printf("The original list is: ");
printList(head);
int k;
printf("Please input the value of k: ");
scanf("%d", &k);
Node *kth = findKthFromEnd(head, k);
if (kth != NULL) {
printf("The %d-th node from the end is: %d\n", k, kth->data);
} else {
printf("The %d-th node from the end does not exist!\n", k);
}
return 0;
}
```