*输入一组整数,以链表形式存储,编写void Reserve (ListNode h),将链表反转。
【输入要求】
1行:
第一行:输入数字的个数
第二行:输入n个数字
【输出要求】
1行:反转后的数字
【输入样例】
6
1 2 3 4 5 6
【输出样例】
6 5 4 3 2 1
#include<stdio.h>
#include<stdlib.h>
#define LEN sizeof(ListNode)
typedef struct su
{
int n;
struct su *next;
}ListNode;
ListNode *Creat_ListNode(int n)//构造单链表
{
int i;
ListNode *h,*p1,*p2;
h=p2=malloc(LEN);
h->next=NULL;
for(i=0;i<n;i++)
{
p1=malloc(LEN);
scanf("%d",&p1->n);
p1->next=NULL;
p2->next=p1;
p2=p1;
}
return h;
}
void Reserve(ListNode *h)//反转链表
{
ListNode *p,*q;
p=h->next;
while(p->next!=NULL)
{
q=p->next;
p->next=q->next;
q->next=h->next;
h->next=q;
}
}
void Output(ListNode *head)
{
ListNode *p;
p=head->next;
if(p!=NULL)
do
{
printf("%d ",p->n);
p=p->next;
}while(p!=NULL);
printf("\n");
int main()
{
int n;
ListNode *head;
scanf("%d",&n);
head=Creat_ListNode(n);
Reserve(head);
Output(head);
return 0;
}