单链表的反序:将已有链表的节点的值反序
废话不多说直接上代码;下面代码提供了两个版本,sll_reverse是我自己做的时候想的笨办法,answer_reverse是我在网上看的一个版本(非常精简)。
#include<stdio.h>
#include <stdlib.h>
#define N 5
typedef struct NODE{
struct NODE *link;
int value;
}Node;
Node* sll_reverse(Node *first);
int insert(Node **linkp,int value) ;
void print(Node* rootp);
unsigned int count(Node*linkp);
struct NODE *answer_reverse( struct NODE *current );
int main (void)
{
Node *p1 = (Node *)malloc( sizeof( Node ) );
p1->link=NULL;
p1->value=5;
int i;
int value;
printf("输入想要插入的值:\n");
while(scanf("%d",&value)==1)
insert(&p1,value);
print(p1);
printf("\n经过反序后,链表中的内容为:\n");
//print(sll_reverse(p1));
print(answer_reverse(p1));
return 0;
}
unsigned int count(Node*linkp)
{
unsigned int num=0;
Node *tmp=linkp;
if(!linkp)
{
printf("link is NULL\n");
exit(1);
}
while(tmp)
{
++num;
tmp=tmp->link;
}
return num;
}
Node* sll_reverse(Node *first)
{
if(first==NULL)//先判断是否是空表
return NULL;
Node *newnode=(Node*)malloc(sizeof(Node));
if(newnode==NULL)
return NULL;
Node*tmp=first;
int n=count(first);//计算已经存在的单链表中的节点数目
int *p=(int*)malloc(n*sizeof(int));//进行动态数组分配
int i=0;
while(tmp!=NULL)//将原链表中节点的数据存储到动态数组中
{
p[i++]=tmp->value;
tmp=tmp->link;
}
newnode->link=NULL;
newnode->value=p[n-1];//创建链表的第一个节点,并把动态数组的最后一个值赋值
for(i=n-2;i>=0;i--)//从动态数组打的倒数第二个数据开始,一次不排序的插入到新链表中
insert(&newnode,p[i]);
return newnode;
}
struct NODE *answer_reverse( struct NODE *current )//答案的版本
{
struct NODE *previous=NULL;
struct NODE *next;
//for( previous = NULL; current != NULL; current = next ){
//next = current->link;
//current->link = previous;
//previous = current;
//}
while(current!=NULL)
{
next=current->link;//next保存原链表的当前指针的下一个指针
current->link=previous;//改变当前指针的执向,也就是构建新的链表
previous=current;//把原链表的第一个节点作为新链表的最后一个节点
current=next;//把next的值赋值给current,直到current==NULL
}
return previous;
}
int insert(Node **linkp,int value)
{
Node *current;
Node *new;
while((current=*linkp)!=NULL)
linkp=¤tt->link;
new=(Node*)malloc(sizeof(struct NODE));
if(new==NULL)
return -1;
new->value=value;
new->link=current;
*linkp=new;
return 0;
}
void print(Node* rootp)
{
if(rootp==NULL)
exit(1);
Node*tmp=rootp;
while(tmp)
{
printf("value=%d\n",tmp->value);
tmp=tmp->link;
}
}