LINUX C 比 vector 更好用的列表 示例
时间: 2024-02-23 21:02:59 浏览: 40
Linux代码,以C、C++为基础.zip
5星 · 资源好评率100%
以下是在 Linux C 中使用双向链表的一个简单示例:
```c
#include <stdio.h>
#include <stdlib.h>
/* 定义双向链表结构体 */
typedef struct Node {
int data;
struct Node* prev;
struct Node* next;
} Node;
/* 初始化双向链表 */
void initList(Node** head) {
*head = NULL;
}
/* 在双向链表头部插入节点 */
void insertAtHead(Node** head, int data) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->prev = NULL;
newNode->next = *head;
if (*head != NULL) {
(*head)->prev = newNode;
}
*head = newNode;
}
/* 在双向链表尾部插入节点 */
void insertAtTail(Node** head, int data) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->next = NULL;
if (*head == NULL) {
newNode->prev = NULL;
*head = newNode;
return;
}
Node* current = *head;
while (current->next != NULL) {
current = current->next;
}
current->next = newNode;
newNode->prev = current;
}
/* 删除双向链表中第一个匹配的节点 */
void deleteNode(Node** head, int data) {
Node* current = *head;
while (current != NULL) {
if (current->data == data) {
if (current == *head) {
*head = current->next;
if (*head != NULL) {
(*head)->prev = NULL;
}
}
else {
current->prev->next = current->next;
if (current->next != NULL) {
current->next->prev = current->prev;
}
}
free(current);
return;
}
current = current->next;
}
}
/* 打印双向链表 */
void printList(Node* head) {
Node* current = head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}
int main() {
Node* head;
initList(&head);
insertAtHead(&head, 1);
insertAtHead(&head, 2);
insertAtHead(&head, 3);
printList(head);
insertAtTail(&head, 4);
insertAtTail(&head, 5);
insertAtTail(&head, 6);
printList(head);
deleteNode(&head, 3);
deleteNode(&head, 6);
printList(head);
return 0;
}
```
在上面的示例中,我们使用了双向链表来实现一个简单的列表,包括在头部插入节点、尾部插入节点和删除节点等操作。
阅读全文