自己没事了随便写的,仅做参考!不好的地方麻烦指出。
友情提示:如果要拷贝这段代码,可以点击代码上方的很小的字--view plain,(不知道你看见没?)然后再全部选中之后再复制。如果直接复制会把左边的行号也复制进去。
#include <stdio.h>
#include <malloc.h>
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;
}