數據結構實驗之鏈表三:鏈表的逆置
Time Limit: 1000ms Memory limit: 65536K 有疑問?點這裏^_^
題目描述
輸入多個整數,以-1作爲結束標誌,順序建立一個帶頭結點的單鏈表,之後對該單鏈表的數據進行逆置,並輸出逆置後的單鏈表數據。
輸入
輸入多個整數,以-1作爲結束標誌。
輸出
輸出逆置後的單鏈表數據。
示例輸入
12 56 4 6 55 15 33 62 -1
示例輸出
62 33 15 55 6 4 56 12
提示
不得使用數組。
來源
示例程序
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
};
struct node *creat()
{
struct node *head,*p,*tail;
head=(struct node *)malloc(sizeof(struct node));
head->next=NULL;
tail=head;
while(1)
{
p=(struct node *)malloc(sizeof(struct node));
scanf("%d",&p->data);
if(p->data==-1)
{
tail->next=NULL;
free(p);
break;
}
tail->next=p;
tail=p;
}
return head;
}
struct node *reverse(struct node *head)
{
struct node *p,*q;
p=head->next;
head->next=NULL;
q=p->next;
while(p!=NULL)
{
p->next=head->next;
head->next=p;
p=q;
if(q!=NULL)
q=q->next;
}
return head;
};
int main()
{
struct node *head,*p;
head=creat();
head=reverse(head);
p=head->next;
while(p!=NULL)
{
(p->next!=NULL)?(printf("%d ",p->data)):(printf("%d",p->data));
p=p->next;
}
return 0;
}