帮我用C语言写一个双向链表
时间: 2023-03-28 16:01:46 浏览: 85
好的,我可以回答这个问题。以下是一个简单的双向链表的 C 语言实现:
```
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* prev;
struct Node* next;
};
struct Node* head = NULL;
struct Node* tail = NULL;
void insertAtBeginning(int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->prev = NULL;
newNode->next = head;
if (head != NULL) {
head->prev = newNode;
} else {
tail = newNode;
}
head = newNode;
}
void insertAtEnd(int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->prev = tail;
newNode->next = NULL;
if (tail != NULL) {
tail->next = newNode;
} else {
head = newNode;
}
tail = newNode;
}
void delete(int data) {
struct Node* current = head;
while (current != NULL) {
if (current->data == data) {
if (current == head) {
head = current->next;
} else {
current->prev->next = current->next;
}
if (current == tail) {
tail = current->prev;
} else {
current->next->prev = current->prev;
}
free(current);
return;
}
current = current->next;
}
}
void printList() {
struct Node* current = head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}
int main() {
insertAtBeginning(1);
insertAtEnd(2);
insertAtEnd(3);
insertAtBeginning(4);
printList();
delete(2);
printList();
return ;
}
```
这个程序实现了双向链表的基本操作,包括在链表头和尾插入节点,删除指定节点,以及打印链表中的所有节点。
阅读全文