Description
输入整数个数N,再输入N个整数,按照这些整数输入的相反顺序建立单链表,并依次遍历输出单链表的数据。
Input
第一行输入整数N;;
第二行依次输入N个整数,逆序建立单链表。
Output
依次输出单链表所存放的数据。
Sample
Input
10
11 3 5 27 9 12 43 16 84 22
Output
22 84 16 43 12 9 27 5 3 11
Hint
不能使用数组!
//用于计时练习上机 14.30
#include<stdio.h>
#include<stdlib.h>
typedef struct a{
int data;
struct a *next;
}LNode;
void create(LNode *&L){//改变L的指向 需要用&或return或全局变量
int n=0,x=0;
L=(LNode*)malloc(sizeof(LNode));
L->next=NULL;L->data=0;
scanf("%d",&n);
for(int i=0;i<n;i++){//采用头插法插入
scanf("%d",&x);
LNode *p=(LNode*)malloc(sizeof(LNode));
p->data=x;
p->next=L->next;
L->next=p;
}
}
int main(){
LNode *L=NULL;
create(L);
LNode *p=L->next;
while(p){//输出漏最后一个或者多第一个元素
//因为p开始指向的L,此时是头结点,while内若是p->next则无法输出最后一个元素
printf("%d ",p->data);
p=p->next;
}
}