可以写一段双链表的初始化,插入,删除,销毁的程序吗?c语言的
时间: 2023-05-20 13:01:04 浏览: 114
数据结构算双链表的初始化 插入 删除 遍历 代码
可以,以下是双链表的初始化、插入、删除和销毁的程序:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node* prev;
struct Node* next;
} Node;
typedef struct List {
Node* head;
Node* tail;
} List;
void initList(List* list) {
list->head = NULL;
list->tail = NULL;
}
void insertNode(List* list, int data) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->prev = NULL;
newNode->next = NULL;
if (list->head == NULL) {
list->head = newNode;
list->tail = newNode;
} else {
newNode->prev = list->tail;
list->tail->next = newNode;
list->tail = newNode;
}
}
void deleteNode(List* list, int data) {
Node* curNode = list->head;
while (curNode != NULL) {
if (curNode->data == data) {
if (curNode == list->head) {
list->head = curNode->next;
if (list->head != NULL) {
list->head->prev = NULL;
}
} else if (curNode == list->tail) {
list->tail = curNode->prev;
if (list->tail != NULL) {
list->tail->next = NULL;
}
} else {
curNode->prev->next = curNode->next;
curNode->next->prev = curNode->prev;
}
free(curNode);
return;
}
curNode = curNode->next;
}
}
void destroyList(List* list) {
Node* curNode = list->head;
while (curNode != NULL) {
Node* nextNode = curNode->next;
free(curNode);
curNode = nextNode;
}
list->head = NULL;
list->tail = NULL;
}
int main() {
List list;
initList(&list);
insertNode(&list, 1);
insertNode(&list, 2);
insertNode(&list, 3);
deleteNode(&list, 2);
destroyList(&list);
return 0;
}
```
其中,initList()函数用于初始化双链表,insertNode()函数用于在双链表末尾插入一个节点,deleteNode()函数用于删除双链表中指定数据的节点,destroyList()函数用于销毁整个双链表。
阅读全文