基于Linux C语言实现双向链表
时间: 2024-12-02 14:16:00 浏览: 11
在Linux环境下,基于C语言实现双向链表通常会涉及到结构体定义、节点创建、指针操作等基本概念。以下是简单步骤:
1. **定义数据结构**:
```c
typedef struct Node {
int data; // 节点存储的数据
struct Node* prev; // 指向前一个节点的指针
struct Node* next; // 指向后一个节点的指针
} Node;
```
2. **创建节点**:
```c
Node* createNode(int data) {
Node* newNode = (Node*)malloc(sizeof(Node));
if (!newNode) {
perror("Memory allocation failed");
return NULL;
}
newNode->data = data;
newNode->prev = NULL;
newNode->next = NULL;
return newNode;
}
```
3. **插入节点**(例如在头部):
```c
void insertAtFront(Node** head, int data) {
Node* newNode = createNode(data);
if (newNode != NULL) {
newNode->next = *head;
if (*head != NULL) {
(*head)->prev = newNode;
}
*head = newNode;
}
}
```
4. **删除节点**(示例删除头节点):
```c
void deleteHead(Node** head) {
if (*head == NULL) {
return;
}
Node* temp = *head;
*head = (*head)->next;
if (*head != NULL) {
(*head)->prev = NULL;
} else {
*head = NULL;
}
free(temp);
}
```
5. **遍历链表**:
```c
void traverseList(Node* head) {
while (head != NULL) {
printf("%d -> ", head->data);
head = head->next;
}
printf("NULL\n");
}
```
阅读全文