天天看點

啊哈,算法中連結清單實作的了解

#include<stdio.h>
#include<stdlib.h>
typedef struct node{
	int value;
	struct node *next;
}Node; 
int main(){
	int number,n,i;
	Node *q,*p,*t,*head;
	scanf("%d",&n);
	head=NULL;
	for(i=0;i<n;i++){
		scanf("%d",&number);
		p=(Node*)malloc(sizeof(Node));
		p->value=number;
		p->next=NULL;
		if(head==NULL)
		head=p;
		else
		q->next=p;
		q=p;
	}
	t=head;
	while(t!=NULL){
		printf("%d",t->value);
		t=t->next;//讓t指向下一個結點(因為t->next指向的就是下一個結點) 
	}
	return 0; 
}
//連結清單的組成:1.一個用來儲存結點的結構體(int資料變量,右邊的部分需要儲存下一個結點的位址,用指針來實作(也成為後繼指針)) 
//2.頭指針,剛開始定義為空,頭指針用來周遊(從頭開始 3)臨時指針,用來建立結點 4)一個last指針,用來結尾。注意這個指針的後繼指針5)用來輸出的指針變量*t
//和自己都需要不斷指向下一個結點(因為後繼指針的作用就是用來儲存下一個結點的位址,而last指針會随着臨時指針的不斷建立而不斷變化位置) 
           

繼續閱讀