目录
什么是双向链表?
双向链表的节点结构
typedef struct Node {
int data;
struct Node* prev;
struct Node* next;
} Node;
双向链表的基本操作
-
初始化双向链表
Node* initLinkedList() { Node* head = (Node*)malloc(sizeof(Node)); head->prev = NULL; head->next = NULL; return head; }
-
插入节点
void insertNode(Node* prevNode, int data) { Node* newNode = (Node*)malloc(sizeof(Node)); newNode->data = data; newNode->prev = prevNode; newNode->next = prevNode->next; prevNode->next->prev = newNode; prevNode->next = newNode;}
3.删除节点
void deleteNode(Node* delNode) {
delNode->prev->next = delNode->next;
delNode->next->prev = delNode->prev;
free(delNode);
}
- 遍历双向链表
void printLinkedList(Node* head) { Node* current = head->next; while (current != NULL) { printf("%d ", current->data); current = current->next; } printf("\\n"); }
完整的双向链表示例
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node* prev;
struct Node* next;
} Node;
Node* initLinkedList() {
Node* head = (Node*)malloc(sizeof(Node));
head->prev = NULL;
head->next = NULL;
return head;
}
void insertNode(Node* prevNode, int data) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->prev = prevNode;
newNode->next = prevNode->next;
prevNode->next->prev = newNode;
prevNode->next = newNode;
}
void deleteNode(Node* delNode) {
delNode->prev->next = delNode->next;
delNode->next->prev = delNode->prev;
free(delNode);
}
void printLinkedList(Node* head) {
Node* current = head->next;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\\n");
}
int main() {
Node* head = initLinkedList();
insertNode(head, 1);
insertNode(head->next, 2);
insertNode(head->next->next, 3);
printLinkedList(head);
deleteNode(head->next);
printLinkedList(head);
return 0;
}
总结
通过上述代码示例,我们实现了双向链表的基本操作,包括初始化、插入和删除节点,以及遍历链表。双向链表是一种灵活且高效的数据结构,适用于需要频繁插入和删除操作的场景。通过深入理解双向链表的实现原理,我们可以更好地应用它解决实际问题。
由以上内容我们其实就可以看到在应用与理解层面,双向链表相较于单向链表有很大的优势,但在具体应用中还需要我们实际情况实际判断。
感谢观看,还请各位大佬点赞支持以下!!!