建立链表单元
struct Node{
int data ;
Node * next ;
};
打印
void print_list(Node * head){
if(head){
printf("%d " , head->data) ;
print_list(head->next) ;
}
}
迭代方式
void * reverse_list(Node ** head){
Node * node_1 , * node_2 , * node_3 ;
node_1 = *head ;//原地守候
node_2 = (*head)->next ;//向前走不回头
while(node_2){//只要还活着
node_3 = node_2->next ;//到前面探探路
node_2->next = node_1 ;//蓦然回首
node_1 = node_2 ;//两情相悦
node_2 = node_3 ;//再度追随
}
(*head)->next = NULL ;
(*head) = node_1 ;//最后的生还者
}
递归方式
void reverse_list(Node ** head){
Node * temp = *head ;
if(temp->next == NULL)
return ;
*head = (*head)->next ;
reverse_list(head) ;
temp->next->next = temp ;//未来的我爱上我
temp->next = NULL ;//没得未来了
}
主函数
#include<stdio.h>
#include<stdlib.h>
int main(){
Node * p4 = (Node *)malloc(sizeof(Node)) ;
p4->data = 4 ; p4->next = NULL ;
Node * p3 = (Node *)malloc(sizeof(Node)) ;
p3->data = 3 ; p3->next = p4 ;
Node * p2 = (Node *)malloc(sizeof(Node)) ;
p2->data = 2 ; p2->next = p3 ;
Node * p1 = (Node *)malloc(sizeof(Node)) ;
p1->data = 1 ; p1->next = p2 ;
Node * head = p1 ;
print_list(head) ;
printf("\n") ;
reverse_list(&head) ;
print_list(head) ;
system("pause");
return 0 ;
}
本文深入讲解链表的基本结构,包括节点定义与初始化,通过示例演示如何创建链表,并提供链表的打印、反转等核心操作的实现代码,采用递归与迭代两种方式对比展示,适合初学者理解链表的工作原理。
1572

被折叠的 条评论
为什么被折叠?



