设为首页 加入收藏

TOP

单向链表的创建和逆转(完整程序)
2014-11-23 23:21:09 来源: 作者: 【 】 浏览:1
Tags:单向 建和 逆转 完整 程序

view plain
#include
#include
typedef struct test
{
int a;
struct test *next;
}lianbiao;


lianbiao* create()//创建链表
{
lianbiao *head,*temp;
int i;
printf("请输入一些整数,以0结束:");
temp=head=(lianbiao *)malloc(sizeof(lianbiao));
scanf("%d",&i);
if(i==0)
{
printf("you input zero!exit now!");
return head;
}
head->a=i;
head->next=NULL;
while(1)
{
scanf("%d",&i);
if(i==0)
break;
else
{
temp->next=(lianbiao *)malloc(sizeof(lianbiao));
temp=temp->next;
temp->a=i;
temp->next=NULL;
}
}
return head;
}
lianbiao* reverse(lianbiao *p)//逆转链表
{
lianbiao *temp1,*temp2;
if(p->next==NULL)
{
printf("链表节点数小于2,无法逆转!\n");
return p;
}
int flag=0;
while(p->next!=NULL)
{
if(flag==0)
{
temp1=p;
temp2=p->next;
p->next=NULL;
p=temp2;
flag=1;
continue;
}
temp2=p->next;
p->next=temp1;
temp1=p;
p=temp2;
}
p->next=temp1;//将原链表的末尾节点指向倒数第二个节点
return p;
}
void print(lianbiao *p)
{
while(p->next!=NULL)
{
printf("%d ",p->a);
p=p->next;
}
printf("%d ",p->a);
printf("\n");
}
int main()
{
lianbiao *temp;
temp=create();
print(temp);//打印出原链表
print(reverse(temp));//打印出逆转后的链表
return 0;
}

作者“simonjay2007的专栏”

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇如何判断单链表中是否存在环 下一篇continue break return switch联..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: