写出实现双向链表的查找前驱、查找后继、从后到前遍历输出等基本操作的C语言程序代码
时间: 2024-01-29 15:03:27 浏览: 68
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node* prev;
struct Node* next;
} Node;
// 创建新节点
Node* createNode(int data) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->prev = NULL;
newNode->next = NULL;
return newNode;
}
// 在链表尾部添加新节点
void append(Node** headRef, int data) {
Node* newNode = createNode(data);
if (*headRef == NULL) {
*headRef = newNode;
return;
}
Node* lastNode = *headRef;
while (lastNode->next != NULL) {
lastNode = lastNode->next;
}
lastNode->next = newNode;
newNode->prev = lastNode;
}
// 在链表头部添加新节点
void prepend(Node** headRef, int data) {
Node* newNode = createNode(data);
if (*headRef == NULL) {
*headRef = newNode;
return;
}
(*headRef)->prev = newNode;
newNode->next = *headRef;
*headRef = newNode;
}
// 查找某个节点的前驱节点
Node* findPrev(Node* head, Node* target) {
if (head == NULL || target == head) {
return NULL;
}
Node* currNode = head;
while (currNode != NULL && currNode->next != target) {
currNode = currNode->next;
}
return currNode;
}
// 查找某个节点的后继节点
Node* findNext(Node* head, Node* target) {
if (head == NULL || target == NULL) {
return NULL;
}
return target->next;
}
// 从后往前遍历输出链表
void reversePrint(Node* head) {
if (head == NULL) {
return;
}
Node* currNode = head;
while (currNode->next != NULL) {
currNode = currNode->next;
}
while (currNode != NULL) {
printf("%d ", currNode->data);
currNode = currNode->prev;
}
printf("\n");
}
int main() {
Node* head = NULL;
append(&head, 1);
append(&head, 2);
append(&head, 3);
prepend(&head, 0);
printf("链表元素:");
Node* currNode = head;
while (currNode != NULL) {
printf("%d ", currNode->data);
currNode = currNode->next;
}
printf("\n");
Node* target = head->next->next;
Node* prevNode = findPrev(head, target);
Node* nextNode = findNext(head, target);
printf("节点 %d 的前驱节点为:%d\n", target->data, prevNode->data);
printf("节点 %d 的后继节点为:%d\n", target->data, nextNode->data);
printf("从后往前遍历输出链表:");
reversePrint(head);
return 0;
}
```
阅读全文