尾插法構建動態單向鏈表-不帶頭結點

本篇目的:編程實現每次輸入數據都插入到單鏈表的尾部。

一、原理

從head開始,基於遍歷算法,找到尾結點,用指針p指向它,將新結點temp鏈接到p的後面。 

二、完整程序

#include <stdio.h>
#include <stdlib.h>

struct node 
{
	int data;
	struct node *next;	
};

struct node* CreateNode(int x)
{//爲數據x生成一個結點
//成功後,返回指向新結點的指針
//失敗後,返回空指針
	struct node *temp;
	temp=(struct node*)malloc(sizeof(struct node));
	if(temp==0)return 0;//失敗
	temp->data=x;//寫入數據
	temp->next=0;//防止指針懸空
	return temp;
}

struct node *find_tail(struct node*head) 
{//主調函數要保證head不能爲空鏈表
//返回最後一個結點的地址
	
	struct node *p=head;
	
	while(p->next!=0)
	{
		p=p->next;
	}	
	
	return p;
}

struct node *push_tail(struct node*head,int t) 
{//head指向的是結第一個點 
//返回插入結點後的鏈表的第一個結點的地址

	struct node *temp;	
	temp=CreateNode(t); //生成一個結點
	if(head==NULL) //鏈表爲空
		return temp;

	struct node *p=find_tail(head);
	p->next=temp;	

	return head;
}

void print_link_list(struct node *head)
{/*//head指向的就是數據,不帶頭結點 **/
	struct node *p=head;
	while(p!=0)
	{
		printf("%d ",p->data);
		p=p->next;
	}
	printf("\n");	
}

int main(void) 
{
	struct node *head=0;
	head=push_tail(head,1);
	print_link_list(head);
	head=push_tail(head,2);
	head=push_tail(head,5);
	head=push_tail(head,8);
	head=push_tail(head,11);	
	print_link_list(head);	
	return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章