用c语言编写一个单链表代码
时间: 2023-10-23 08:10:00 浏览: 89
好的,请看下面的代码:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int data;
struct node *next;
} Node;
void insert(Node **head, int data) {
Node *temp = (Node*) malloc(sizeof(Node));
temp->data = data;
temp->next = *head;
*head = temp;
}
void delete(Node **head, int data) {
Node *temp = *head;
Node *prev;
if (temp != NULL && temp->data == data) {
*head = temp->next;
free(temp);
return;
}
while (temp != NULL && temp->data != data) {
prev = temp;
temp = temp->next;
}
if (temp == NULL)
return;
prev->next = temp->next;
free(temp);
}
void printList(Node *head) {
while (head != NULL) {
printf("%d ", head->data);
head = head->next;
}
}
int main() {
Node *head = NULL;
insert(&head, 1);
insert(&head, 2);
insert(&head, 3);
insert(&head, 4);
insert(&head, 5);
printf("List before deletion: ");
printList(head);
delete(&head, 3);
printf("\nList after deletion: ");
printList(head);
return 0;
}
```
以上是用 C 语言编写的单链表代码,它包括创建一个节点、向链表中插入节点、从链表中删除节点以及打印链表中所有节点的方法。通过这个代码,可以从头到尾遍历单链表并对它进行操作。
阅读全文