本文主要是介绍单双链表反转,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
单链表反转
#include <stdio.h>
#include <stdlib.h>// 定义链表节点结构
struct Node {int data;struct Node* next;
};// 反转链表函数
struct Node* reverseList(struct Node* head) {struct Node* prev = NULL;struct Node* current = head;struct Node* next = NULL;while (current != NULL) {next = current->next; // 保存下一个节点的指针current->next = prev; // 反转当前节点的指针prev = current; // 更新 prev 指针current = next; // 更新 current 指针}head = prev; // 更新头指针为新的链表头return head;
}// 输出链表内容函数
void printList(struct Node* node) {while (node != NULL) {printf("%d ", node->data);node = node->next;}printf("\n");
}int main() {struct Node* head = NULL;struct Node* second = NULL;struct Node* third = NULL;// 分配节点内存head = (struct Node*)malloc(sizeof(struct Node));second = (struct Node*)malloc(sizeof(struct Node));third = (struct Node*)malloc(sizeof(struct Node));// 设置节点数据head->data = 1;head->next = second;second->data = 2;second->next = third;third->data = 3;third->next = NULL;printf("Original list: \n");printList(head);// 反转链表head = reverseList(head);printf("Reversed list: \n");printList(head);return 0;
}
双链表反转
#include <stdio.h>
#include <stdlib.h>// 定义双向链表节点结构
struct Node {int data;struct Node* next;struct Node* prev;
};// 反转双向链表函数
struct Node* reverseDoublyLinkedList(struct Node* head) {struct Node* temp = NULL;struct Node* current = head;// 交换每个节点的 prev 和 next 指针while (current != NULL) {temp = current->prev;current->prev = current->next;current->next = temp;current = current->prev; // 移动到下一个节点}// 更新头指针为新的链表头if (temp != NULL) {head = temp->prev;}return head;
}// 输出双向链表内容函数
void printDoublyList(struct Node* node) {struct Node* last = NULL;printf("\n从前往后打印链表:\n");while (node != NULL) {printf("%d ", node->data);last = node;node = node->next;}printf("\n从后往前打印链表:\n");while (last != NULL) {printf("%d ", last->data);last = last->prev;}printf("\n");
}int main() {struct Node* head = NULL;struct Node* second = NULL;struct Node* third = NULL;// 分配节点内存head = (struct Node*)malloc(sizeof(struct Node));second = (struct Node*)malloc(sizeof(struct Node));third = (struct Node*)malloc(sizeof(struct Node));// 设置节点数据head->data = 1;head->prev = NULL;head->next = second;second->data = 2;second->prev = head;second->next = third;third->data = 3;third->prev = second;third->next = NULL;printf("Original list: ");printDoublyList(head);// 反转双向链表head = reverseDoublyLinkedList(head);printf("Reversed list: ");printDoublyList(head);return 0;
}
这篇关于单双链表反转的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!