目录
数据结构
链表的数据结构定义:
typedef struct list_node{ //链表节点
int data;
struct list_node * next;
}list_node, * list_node_p;
typedef struct list_head{ //链表头
list_node_p next;
int count;
}list_head,* list_head_p;
链表的数据存储方式:
逆序实现的方法
本文主要讨论两种逆序方法:
- 头结点插入法
- 对称交换法
1.头结点插入法描述如下:
以包含四个元素、带有头结点的链表l为例:
head->a1->a2->a3->a4;
保持头结点不变,头插法实现链表反转步骤为:
1: 将a2插在a1前面,该链表变为:
head->a2->a1->a3->a4;
2: 将a3插在a2前面,该链表变为:
head->a3->a2->a1->a4;
3: 将a4插在a3前面,该链表变为:
head->a4->a3->a2->a1;
可以发现,此时已经完成了链表的反转。
2.对称交换法描述如下:
同样以包含四个元素、带有头结点的链表l为例:
head->a1->a2->a3->a4;
1.头结点不变,对称交换a1和a2
head a1<-a2 a3->a4;
2.对称交换a2和a3
head a1<-a2<-a3 a4;
3.对称交换a3和a4
head a1<-a2<-a3<-a4;
4.调整头结点位置
a1<-a2<-a3<-a4<-head ;
可以发现,此时已经完成了链表的反转。
实例代码
#include <stdio.h>
#include <stdlib.h>
#define NUM 10 //链表大小
typedef struct list_node{
int data;
struct list_node * next;
}list_node, * list_node_p;
typedef struct list_head{
list_node_p next;
int count;
}list_head,* list_head_p;
int reverse_1(list_head_p head){ //逆序链表算法一(对称交换)
list_node_p cur;
list_node_p pre;
list_node_p net;
printf("%s\n",__func__);
pre = NULL;
cur=head->next;
while(cur!=NULL){
net=cur->next;
cur->next=pre;
pre=cur;
cur=net;
}
head->next=pre;
return 0;
}
int reverse_2(list_head_p head){ //逆序链表算法二(头结点插入)
list_node_p cur;
list_node_p pre;
list_node_p sec;
printf("%s\n",__func__);
pre=head->next;
cur=pre->next;
sec=head->next;
while(cur!=NULL){
pre->next=cur->next;
head->next=cur;
cur->next=sec;
sec=cur;
cur=pre->next;
}
return 0;
}
int print_list(list_head_p head){
list_node_p node = head->next;
while(node!=NULL){
printf("%d ",node->data);
node=node->next;
}
printf("\n");
return 0;
}
int init_list(list_head_p head){
int i ;
list_node_p temp=NULL;
list_node_p tail=NULL;
printf("%s\n",__func__);
temp=(list_node_p )malloc(sizeof(list_node_p));
head->next=temp;
temp->data = 0;
for (i=1;i<NUM;i++){
temp->next=(list_node_p )malloc(sizeof(list_node_p));
temp->next->data =i;
temp=temp->next;
head->count++;
}
temp->next = NULL;
return 0;
}
int main(){
list_head_p head;
head=(list_head_p)malloc(sizeof(list_head));
init_list(head);
print_list(head);
reverse_1(head);
print_list(head);
reverse_2(head);
print_list(head);
return 0;
}
运行结果如下:
init_list
0 1 2 3 4 5 6 7 8 9
reverse_1
9 8 7 6 5 4 3 2 1 0
reverse_2
0 1 2 3 4 5 6 7 8 9