數據結構實驗之鏈表一:順序建立鏈表

數據結構實驗之鏈表一:順序建立鏈表

Time Limit: 1000 ms Memory Limit: 65536 KiB

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

不得使用數組!

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;
}

發佈了72 篇原創文章 · 獲贊 9 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章