您的位置:首页 > 其它

初始化单链表,并在只遍历一次的情况下倒序

2011-11-24 23:00 399 查看
/*
初始化单链表,并在只遍历一次的情况下倒序
*/

#include<stdio.h>
#include<stdlib.h>
typedef struct Node
{
int data;
struct Node *next;
}node;
struct Node * nodeinit(void) //构建单链表
{
node *head,*p,*q;
head=(node*)malloc(sizeof node);
int x=0,n=0;
while(1)
{
printf("input the number:\n");
scanf("%d",&x);
if(x==0)
{
break;
}
else
{
p=(node *)malloc(sizeof node);
p->data=x;
if(++n==1)
{
head->next=p;
}
else
{
q->next=p;
}

q=p;
}
}
p->next=NULL;
return head;
}

void showlist(struct Node *head) //打印单链表
{
printf("the list is:\n");
struct Node *p=head->next;
while(p!=NULL)
{
printf("%d\n",p->data);
p=p->next;
}
}

struct Node * resetlist(struct Node *head) //单链表倒序
{
printf("start reset!\n");
struct Node *p,*q;
p=head->next;
while(p!=NULL)
{
q=p;
p=p->next;
q->next=head->next;
if(q->next==q)
{
q->next=NULL;
}
head->next=q;
}
printf("success reset!\n");

return head;
}

int main()
{
struct Node *head1,*head2;

head1=nodeinit();
showlist(head1);

head2=resetlist(head1);
showlist(head2);

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐