用c语言实现双向链表的基本操作
时间: 2023-10-11 10:10:59 浏览: 90
双向链表的基本操作包括创建、插入、删除和遍历等操作。以下是用C语言实现双向链表的基本操作的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* prev;
struct Node* next;
};
struct Node* createNode(int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->prev = NULL;
newNode->next = NULL;
return newNode;
}
void insertAtBeginning(struct Node** headRef, int data) {
struct Node* newNode = createNode(data);
newNode->next = *headRef;
if (*headRef != NULL) {
(*headRef)->prev = newNode;
}
*headRef = newNode;
}
void insertAtEnd(struct Node** headRef, int data) {
struct Node* newNode = createNode(data);
struct Node* lastNode = *headRef;
if (*headRef == NULL) {
*headRef = newNode;
return;
}
while (lastNode->next != NULL) {
lastNode = lastNode->next;
}
lastNode->next = newNode;
newNode->prev = lastNode;
}
void deleteNode(struct Node** headRef, int key) {
struct Node* nodeToDelete = *headRef;
if (nodeToDelete != NULL && nodeToDelete->data == key) {
*headRef = nodeToDelete->next;
if (*headRef != NULL) {
(*headRef)->prev = NULL;
}
free(nodeToDelete);
return;
}
while (nodeToDelete != NULL && nodeToDelete->data != key) {
nodeToDelete = nodeToDelete->next;
}
if (nodeToDelete == NULL) {
printf("Node with key %d not found\n", key);
return;
}
nodeToDelete->prev->next = nodeToDelete->next;
if (nodeToDelete->next != NULL) {
nodeToDelete->next->prev = nodeToDelete->prev;
}
free(nodeToDelete);
}
void printList(struct Node* node) {
while (node != NULL) {
printf("%d ", node->data);
node = node->next;
}
printf("\n");
}
int main() {
struct Node* head = NULL;
insertAtEnd(&head, 1);
insertAtEnd(&head, 2);
insertAtBeginning(&head, 3);
printList(head);
deleteNode(&head, 1);
printList(head);
return 0;
}
```
在上述代码中,我们定义了一个`Node`结构体来表示双向链表中的节点。`createNode`函数用于创建一个新的节点,`insertAtBeginning`函数用于在链表头部插入一个节点,`insertAtEnd`函数用于在链表尾部插入一个节点,`deleteNode`函数用于删除指定数据的节点,`printList`函数用于遍历并打印链表中的所有数据。在`main`函数中,我们创建了一个空链表,然后依次执行了插入操作和删除操作,并打印了最终的链表。
阅读全文