在C语言中如何实现双链表的基本操作(如插入节点、删除节点和遍历)使用尾插法?
时间: 2024-10-20 14:02:24 浏览: 32
C语言 数据结构双向链表简单实例
在C语言中,使用尾插法(也叫“尾追法”)实现双链表的基本操作通常涉及以下几个步骤:
1. **结构体定义**:
```c
typedef struct Node {
int data;
struct Node* next;
struct Node* prev; // 双向链表特有的指向前一个节点的指针
} Node;
```
2. **插入节点** (尾部插入):
```c
void insertAtEnd(Node** head, int data) {
if (*head == NULL) {
*head = (Node*)malloc(sizeof(Node));
(*head)->data = data;
(*head)->prev = NULL;
(*head)->next = NULL;
} else {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->prev = (*head)->prev;
newNode->next = *head;
if ((*head)->prev != NULL)
(*head)->prev->next = newNode;
else
newNode->prev = NULL;
(*head)->prev = newNode;
}
}
```
3. **删除节点**:
```c
void deleteNode(Node** head, int key) {
Node* temp = *head;
while (temp != NULL && temp->data != key) {
temp = temp->next;
}
if (temp == NULL) return;
// 如果要删除的是头结点
if (temp == *head) {
*head = temp->next;
if (*head != NULL) (*head)->prev = NULL;
free(temp);
} else {
temp->prev->next = temp->next;
if (temp->next != NULL) temp->next->prev = temp->prev;
free(temp);
}
}
```
4. **遍历双链表** (尾部开始的反向遍历):
```c
void printListBackward(Node* node) {
while (node != NULL) {
printf("%d ", node->data);
node = node->prev;
}
printf("\n");
}
```
阅读全文