链表-简单练习题1-数据结构实验之链表一:顺序建立链表 SDUT2117

Problem Description

输入N个整数,按照输入的顺序建立单链表存储,并遍历所建立的单链表,输出这些数据。

Input

第一行输入整数的个数N;
第二行依次输入每个整数。

Output

输出这组整数。

Sample Input

8
12 56 4 6 55 15 33 62

Sample Output

12 56 4 6 55 15 33 62

Hint

不得使用数组!
 
 
 
详细链表解释参见另一篇随笔。
 
 
代码如下:
 1 #include<iostream>
 2 #include<cstdlib>
 3 using namespace std;
 4 struct INT{
 5     int num;
 6     struct INT *pnext;
 7 };
 8 
 9 int main(){
10     int N;
11     cin>>N;
12     INT* head=(INT*)malloc(sizeof(INT));
13     head->pnext=NULL;//创建链表头结点 
14     INT* P=head;
15     
16     for(int i=0;i<N;i++){
17         INT* pNew=(INT*)malloc(sizeof(INT));
18         cin>>pNew->num;
19         pNew->pnext=NULL;//这一步特别重要!
20         
21         P->pnext=pNew;
22         P=P->pnext;
23     }//添加n个节点
24     
25     P=head->pnext;//令P指向第一个有数据的节点
26     while(P!=NULL){
27         cout<<P->num<<" ";
28         P=P->pnext;
29     } 
30     cout<<endl;
31      
32     
33     return 0;
34 } 

猜你喜欢

转载自www.cnblogs.com/juzijuziju/p/11376800.html