數據結構實驗之鏈表一:順序建立鏈表
Problem Description
Input
第二行依次輸入每個整數。
Output
Sample Input
8 12 56 4 6 55 15 33 62
Sample Output
12 56 4 6 55 15 33 62
Hint
Source
感悟:還是要一點一點看,不理解的就動手畫一畫,不要畏難,其實很簡單的。
#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<cstdlib>
using namespace std;
struct node{//設置結構體,表示鏈表;
int date;//數據域
struct node *next;//struct node型指針,指向後繼。
};
int main(){
int i;
int n;// 輸入鏈表中數字的個數
cin>>n;
struct node *head,*tail,*p;//設置了三個struct node類型的指針,分別表示頭指針,過程指針,和接收數據的指針。
head=(struct node *)malloc(sizeof(struct node));//用動態分配malloc給頭指針分配空間。
head->next=NULL;//讓頭指針指向空。
tail=head;//讓尾指針等於頭指針表示鏈表爲空。
for(i=0;i<n;i++){//輸入幾個數
p=(struct node *)malloc(sizeof(struct node));//分配給指針p存儲空間。
scanf("%d",&p->date);//收到數字,並存到p的數據域裏。
p->next=NULL;//讓p的後繼爲空
tail->next=p;//讓tail的後繼指向p,也就是head指向p。由此使得兩個原本沒有關係的存儲空間鏈接起來。
tail=p;//讓tail與p相等,等待下一個帶鏈接的存儲空間。
}
tail=head->next;//for循環結束後,tail指向的是最後的那個存儲空間。 讓指向 head->next,指的是第一個有數據域的存儲空間。
while(tail!=NULL){//由頭遍歷到尾
printf("%d",tail->date);//輸出數據域
if(tail->next!=NULL){//輸出要求,兩個數字之間要有空格。
printf(" ");
}
tail=tail->next;//使tail指向鏈表的下一個元素。
}
printf("\n");//題目要求。
return 0;
}