用c语言建立双向链表,并在双向链表上实现插入、删除和查找操作
时间: 2024-04-29 15:22:29 浏览: 10
好的,下面是用 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 insertAtEnd(struct node **head, int data) {
struct node *newNode = createNode(data);
if (*head == NULL) {
*head = newNode;
return;
}
struct node *temp = *head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newNode;
newNode->prev = temp;
}
// 在链表头部插入节点
void insertAtBeginning(struct node **head, int data) {
struct node *newNode = createNode(data);
if (*head == NULL) {
*head = newNode;
return;
}
newNode->next = *head;
(*head)->prev = newNode;
*head = newNode;
}
// 删除指定节点
void deleteNode(struct node **head, int key) {
struct node *temp = *head;
if (temp != NULL && temp->data == key) {
*head = temp->next;
(*head)->prev = NULL;
free(temp);
return;
}
while (temp != NULL && temp->data != key) {
temp = temp->next;
}
if (temp == NULL) {
printf("Node with data %d not found.\n", key);
return;
}
temp->prev->next = temp->next;
if (temp->next != NULL) {
temp->next->prev = temp->prev;
}
free(temp);
}
// 查找节点
void searchNode(struct node *head, int key) {
struct node *temp = head;
while (temp != NULL && temp->data != key) {
temp = temp->next;
}
if (temp == NULL) {
printf("Node with data %d not found.\n", key);
return;
}
printf("Node with data %d found at address %p.\n", key, temp);
}
// 打印链表
void printList(struct node *head) {
if (head == NULL) {
printf("The list is empty.\n");
return;
}
struct node *temp = head;
printf("List: ");
while (temp != NULL) {
printf("%d ", temp->data);
temp = temp->next;
}
printf("\n");
}
int main() {
struct node *head = NULL;
insertAtEnd(&head, 10);
insertAtEnd(&head, 20);
insertAtEnd(&head, 30);
insertAtBeginning(&head, 5);
insertAtBeginning(&head, 0);
printList(head);
deleteNode(&head, 20);
printList(head);
searchNode(head, 10);
searchNode(head, 20);
return 0;
}
```
这个程序创建了一个双向链表,然后在链表末尾和链表头部插入节点,通过删除节点和查找节点操作来修改链表,最后打印出链表的内容。