c语言数据结构分析1之 链表创建

#include <stdlib.h>
#include <stdio.h>
struct test{

	int value;

	struct test *next;

};

struct test* create(){ //创建create 函数,返回 struct test* 结构指针 返回的是头部指针

	test *head,*tail,*p;

	head=tail=NULL;

	//head 是保存头部指针,p是当前指针,tail是临时替换的指针,是用来过度的

	int i;

	while(scanf("%d",&i)==1)

	{

		//(数据类型)malloc(sizeof(数据类型)) 动态分配内存,一定要记得用free() 消毁

		p=(struct test*)malloc(sizeof(struct test)); //创建结构并开屁空间

		p->value=i;

		p->next=NULL;



		if(head==NULL)

		{

			head=tail=p;		//保存头部指针 并且关联 指针 p,也就是返回的head 可以关联到 p

		}

		else{

			tail=tail->next;	//第二次set tail->next 有值了 相当于移动两个变量 的指针

         //保存上一次指针

		}

		tail->next=p;			//当前指针追加在未尾;

	}



	return head;

};

int main(int argc, char* argv[])

{



	struct test *p,*n;

	p=create();

	while(p)

	{

		printf("%d\n",p->value);

		n=p->next;

		free(p);

		p=n;

	}



	return 0;

}
  

  

posted @ 2011-08-14 16:51  solq  阅读(368)  评论(0编辑  收藏  举报