初始化单链表,并在只遍历一次的情况下倒序
/*
初始化单链表,并在只遍历一次的情况下倒序
*/
#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;
}