#include <stdio.h>
#include <stdlib.h>
/********说明:不需要额外申请空间对链表进行逆序算法**************/
/*链表节点*/
typedef struct Node
{
int data;
struct Node *next;
}node;
/*链表控制节点*/
typedef struct
{
node *head;
int cnt; //节点个数
}ndctl;
void create_lianbiao(ndctl *ctl,int lenth);
void reserve(ndctl *ctl);
void print(ndctl *ctl);
int main(int argc,char *argv[])
{
ndctl ctl = {NULL,0} ;
int num = 0;
if(argc!=2){
printf("para is illegal!\n");
exit(0);
}
num=atoi(argv[1]);
create_lianbiao(&ctl,num);
print(&ctl);
reserve(&ctl);
printf("--------------after reversion-----------------------\n");
print(&ctl);
printf("-----------------------------------------------------\n");
return 0;
}
//创建链表
void create_lianbiao(ndctl *ctl,int lenth)
{
node *pnt = NULL;
node *tmp = NULL;
int count= 1 ;
while(ctl->cnt < lenth ){
pnt =(node *)malloc(sizeof(node));
if(pnt == NULL){
printf("malloc failure!\n");
exit(0);
}
pnt->data = count;
count++;
pnt->next = NULL ;
if(ctl->cnt == 0){
ctl->head=pnt;
ctl->cnt++;
}else{
tmp=ctl->head; //头插法是链表(栈)
ctl->head = pnt;
pnt->next = tmp;
ctl->cnt++;
}
}
}
/*reverseion method*/
void reserve(ndctl *ctl)
{
if(ctl->cnt < 2){ //如果链表只有一个节点,则不需要逆序
//nothing
}else{
node *tmp = NULL ;
node *end = ctl->head ; //保存头节点的位置
node *h1 = ctl->head->next ; //h1指向头节点的下一位
while(h1!=NULL){
if(h1->next!=NULL){
tmp = ctl->head ; //保存头节点位置到tmp
ctl->head = h1 ; //头节点向后移到h1
h1 = h1->next ; //h1向后移动一位
ctl->head->next = tmp ; //头节点指向之前的位置tmp
}else{
tmp = ctl->head ;
ctl->head = h1 ;
h1 = NULL ;
ctl->head->next = tmp ;
end->next = NULL ; //排序完成后,最初的头节点变成尾
} //节点,此时尾节点指向NULL
}
printf("\n");
}
}
/*打印链表*/
void print(ndctl *ctl)
{
if(ctl->head == NULL){
printf(" the list is null\n");
exit(0);
}
node *pnt = ctl->head;
printf("the list is :\n");
while(pnt!= NULL){
printf("%4d",pnt->data);
if(pnt->next !=NULL){
pnt=pnt->next;
}else{
break;
}
}
printf("\n");
}
/********Copyright @2014 Cupertino All rights reserved********/
链表逆序(无需申请额外空间c语言版)
最新推荐文章于 2023-01-15 10:42:20 发布