从键盘输入任意多个正整数,输入以-1结束。逆序输出这些整数(不包括-1)。 提示: 1、逆序创建单链表。结点数据域是整型数。每输入一个整数,向链表中插入一个结点。当输入-1时结束链表的创建。 2、遍历链表,输出结点数据域的值。 3、遍历完成后,要求销毁该链表。
输入格式:
任意多的正整数,输入序列以-1结束。
输出格式:
逆序输出这些整数(不包括-1)。
输入样例:
在这里给出一组输入。例如:
3 8 2 9 7 4 -1
结尾无空行
输出样例:
在这里给出相应的输出。例如:
4 7 9 2 8 3
结尾无空行
#include<stdio.h>
#include<stdlib.h>
typedef struct node
{
int data;
struct node *next;
}*list;
list creat()//逆序建立链表
{
list head,p;
int n;
head=(list)malloc(sizeof(struct node));
head->next=NULL;
while(scanf("%d",&n)&&n!=-1)
{
p=(list)malloc(sizeof(struct node));
p->data=n;
p->next=head->next;
head->next=p;
}
return head;
}
void print(list head)
{
list p;
p=head->next;
while(p!=NULL)
{
printf("%d ",p->data);
p=p->next;
}
}
int main()
{
list head;
head=creat();
print(head);
free(head);
return 0;
}