c语言 数据结构 设有头结点单链表,删除单链表中倒数第k个结点。第一行输入若干个整数建立带头结点的单链表,以e结尾。 第二行输入一个整数k,表示删除倒数第k个结点。输出删除后单链表的所有元素。
时间: 2024-05-03 12:21:17 浏览: 70
```
#include <stdio.h>
#include <stdlib.h>
typedef int ElemType;
typedef struct Node {
ElemType data;
struct Node *next;
} Node, *LinkList;
LinkList createList() {
LinkList head = (LinkList) malloc(sizeof(Node));
head->next = NULL;
LinkList p = head;
ElemType x;
scanf("%d", &x);
while (x != -1) {
LinkList newNode = (LinkList) malloc(sizeof(Node));
newNode->data = x;
newNode->next = NULL;
p->next = newNode;
p = newNode;
scanf("%d", &x);
}
return head;
}
void printList(LinkList head) {
LinkList p = head->next;
while (p) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
void deleteKthFromEnd(LinkList head, int k) {
LinkList p = head->next, q = head->next, pre = head;
int cnt = 0;
while (q && cnt < k) {
q = q->next;
cnt++;
}
while (q) {
p = p->next;
q = q->next;
pre = pre->next;
}
pre->next = p->next;
free(p);
}
int main() {
LinkList list = createList();
int k;
scanf("%d", &k);
deleteKthFromEnd(list, k);
printList(list);
return 0;
}
```
阅读全文