linux c 双向链表
时间: 2023-07-11 08:41:16 浏览: 114
c语言实现的双向链表
双向链表是一种链表,每个节点包含两个指针,分别指向前一个节点和后一个节点,这样每个节点既可以访问它前面的节点,也可以访问它后面的节点。
下面是一个简单的双向链表的示例代码,包含创建、插入、删除和遍历等操作:
```c
#include <stdio.h>
#include <stdlib.h>
// 双向链表节点定义
typedef struct node {
int data;
struct node *prev;
struct node *next;
} Node;
// 创建双向链表
Node* create_list(int arr[], int len) {
Node *head, *tail, *p;
head = tail = NULL;
for (int i = 0; i < len; i++) {
p = (Node*)malloc(sizeof(Node));
p->data = arr[i];
p->prev = tail;
p->next = NULL;
if (tail != NULL) {
tail->next = p;
}
tail = p;
if (head == NULL) {
head = p;
}
}
return head;
}
// 插入节点
void insert_node(Node *prev, int data) {
Node *p = (Node*)malloc(sizeof(Node));
p->data = data;
p->prev = prev;
p->next = prev->next;
prev->next = p;
if (p->next != NULL) {
p->next->prev = p;
}
}
// 删除节点
void delete_node(Node *p) {
if (p->prev != NULL) {
p->prev->next = p->next;
}
if (p->next != NULL) {
p->next->prev = p->prev;
}
free(p);
}
// 遍历链表
void traverse_list(Node *head) {
Node *p = head;
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
int main() {
int arr[] = {1, 2, 3, 4, 5};
int len = sizeof(arr) / sizeof(arr[0]);
Node *head = create_list(arr, len);
printf("Original list: ");
traverse_list(head);
insert_node(head->next, 6);
printf("After inserting 6: ");
traverse_list(head);
delete_node(head->next->next);
printf("After deleting node 3: ");
traverse_list(head);
return 0;
}
```
输出结果为:
```
Original list: 1 2 3 4 5
After inserting 6: 1 2 6 3 4 5
After deleting node 3: 1 2 6 4 5
```
阅读全文