c语言 数据结构链表删除完整代码
时间: 2023-12-07 10:38:58 浏览: 29
以下是C语言数据结构链表删除的完整代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义链表节点结构体
typedef struct node {
int data;
struct node *next;
} Node;
// 创建链表
Node *createList(int n) {
Node *head = NULL, *tail = NULL, *p = NULL;
int i, data;
for (i = 0; i < n; i++) {
printf("请输入第%d个节点的值:", i + 1);
scanf("%d", &data);
p = (Node *)malloc(sizeof(Node));
p->data = data;
p->next = NULL;
if (head == NULL) {
head = p;
tail = p;
} else {
tail->next = p;
tail = p;
}
}
return head;}
// 删除链表中指定值的节点
Node *deleteNode(Node *head, int value) {
Node *p = head, *q = NULL;
while (p != NULL) {
if (p->data == value) {
if (p == head) {
head = head->next;
} else {
q->next = p->next;
}
free(p);
break;
}
q = p;
p = p->next;
}
return head;
}
// 输出链表
void printList(Node *head) {
Node *p = head;
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
int main() {
int n, value;
Node *head = NULL;
printf("请输入链表的长度:");
scanf("%d", &n);
head = createList(n);
printf("请输入要删除的节点的值:");
scanf("%d", &value);
head = deleteNode(head, value);
printf("删除节点后的链表为:");
printList(head);
return 0;
}
```