天天看点

啊哈,算法中链表实现的理解

#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指针会随着临时指针的不断创建而不断变化位置) 
           

继续阅读