單向鏈表的創建與打印

          最近在學數據結構,以前學校學的太水了,自己重新看一遍吧,先從最簡單的開始吧,來個單向鏈表的創建與打印

                 <pre name="code" class="cpp">#include<stdio.h>
#include<malloc.h>
	struct node
	{
		 int data;     //elementype表示一種數據類型,可能是int/char等等
		 struct node *next;   //next 指針,用於鏈表結構指向下一個節點
	};
	typedef struct node node; //重定義struct node類型爲node

	void List(node* head);
	node* Creat();
	int main()
	{
	node* head;
	head = Creat();
	List(head);
	return 0;
	}
	int n;
	node* Creat()
	{
		node *p1,*p2,*head;
		n = 0;
		p1 = p2 = (node*)malloc(sizeof(node));
		scanf("%d",&p1->data);
		head = NULL;
		while(p1->data!=0)
		{
			n = n+1;
			if(n == 1)
			{
				head = p1;

			}
			else
			{
				p2->next = p1;

			}
			p2 = p1;
			p1 = (node*)malloc(sizeof(node));
			scanf("%d",&p1->data);

		}
		p2->next = NULL;
		return(head);
	}
	void List(node* head)
	{
		node *p1;
		p1 = head;
		while(p1!= NULL)
		{
			
			printf("%d\n",p1->data);
			p1 = p1->next;
		}
	}



運行結果:


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