Time Limit: 1000 ms Memory Limit: 65536 KiB
Submit Statistic
Problem Description
输入整数个数N,再输入N个整数,按照这些整数输入的相反顺序建立单链表,并依次遍历输出单链表的数据。
Input
第一行输入整数N;; 第二行依次输入N个整数,逆序建立单链表。
Output
依次输出单链表所存放的数据。
Sample Input
10 11 3 5 27 9 12 43 16 84 22Sample Output
22 84 16 43 12 9 27 5 3 11Hint
不能使用数组!
Source
逆序建立链表是学习链表的基本步骤,逆序链表的建立其实就是每次新输入的数据都放在头结点的后面,可以考虑一个已经有好多结点的链表,现在建立一个新的结点P,输入数据之后要放在头结点的后面,其实就是先让新结点P的下一个等于头结点的下一个,这样新结点的出路就通了。然后再让头结点的下一个等于P,同理就是新结点的入口通了,这样就可以一个一个逆序建立起来链表。
同样这里给出两种语言的代码:
AC代码:
C++:
#include<bits/stdc++.h> using namespace std; typedef struct node { int data; struct node*next; }tree[1100]; int main() { struct node*head,*tail,*p; head=new tree; head->next=NULL; int n; scanf("%d",&n); for(int i=0;i<n;i++) { p=new tree; scanf("%d",&p->data); p->next=head->next; head->next=p; } p=head->next; while(p) { if(p->next==NULL) { printf("%d\n",p->data); } else { printf("%d ",p->data); } p=p->next; } return 0; }C:
#include<stdio.h> #include<stdlib.h> //注意头文件,要不然malloc函数无法被编译器识别 struct node { int data; struct node*next; }tree[1100]; int main() { struct node*head,*tail,*p; head=(struct node*)malloc(sizeof(struct node)); head->next=NULL; int n; scanf("%d",&n); for(int i=0;i<n;i++) { p=(struct node*)malloc(sizeof(struct node)); scanf("%d",&p->data); p->next=head->next; head->next=p; } p=head->next; while(p) { if(p->next==NULL) { printf("%d\n",p->data); } else { printf("%d ",p->data); } p=p->next; } return 0; }