输出带头结点单链表的函数
时间: 2023-08-31 13:10:41 浏览: 95
以下是带头结点单链表的函数实现:
```
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node* next;
} Node, *LinkedList;
LinkedList createLinkedList() {
LinkedList L = (LinkedList)malloc(sizeof(Node));
L->next = NULL;
return L;
}
void insert(LinkedList L, int data) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->next = L->next;
L->next = newNode;
}
void delete(LinkedList L, int data) {
Node* p = L->next;
Node* pre = L;
while (p != NULL) {
if (p->data == data) {
pre->next = p->next;
free(p);
return;
}
pre = p;
p = p->next;
}
}
void display(LinkedList L) {
Node* p = L->next;
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
void destroy(LinkedList L) {
Node* p = L->next;
while (p != NULL) {
Node* next = p->next;
free(p);
p = next;
}
free(L);
}
int main() {
LinkedList L = createLinkedList();
insert(L, 1);
insert(L, 2);
insert(L, 3);
display(L);
delete(L, 2);
display(L);
destroy(L);
return 0;
}
```
阅读全文