单链表的创建与输出

单链表又叫线性链表或单向链表。它是线性表的来链接储存表示。使用单链表储存结构时,其数据元素只存在逻辑联系而不存在物理联系,能够很好的解决数据溢出问题。单链表中的每个数据都储存在链表节点中,每个节点结构体中有两个储存域:数据域和指针域。其中,数据域中储存链表节点的数据元素,指针域储存了指向该链表节点的下一个节点的指针。

链表结构体如下所示:

typedef struct node{			
	int data;
	struct  node *next;
}*List;                            //*List代表将结构体中的指针类型

单链表的创建及输出代码如下:

#include<iostream>
using namespace std;
typedef struct node{
	int data;                  //数据域
	struct node *next;         //指针域
}node;                             //链表结构体的定义

struct node *Create()              //链表创建函数
{
	struct node *head,*p,*tail;
	cout<<"请输入链表数据,以0结束!!!"<<endl;
	head=p=tail=new node;
	cin>>p->data;
	
	while(p->data!=0)
	{
		tail->next=p;
		tail=p;
		
		p=new node;
		cin>>p->data;
	}
	tail->next=NULL;
	cout<<"链表创建完毕!!!"<<endl;
	return head;               //返回链表头指针
}

void Show(node *head)              //链表输出函数
{
	node *p;
	p=head;
	while(p)
	{
		cout<<p->data<<" ";
		p=p->next;
	}
	cout<<endl; 
	cout<<"链表输出完毕!!!"<<endl;
}

int main()
{
	struct node *head;
	head=Create();
	Show(head);
        return 0;
}

猜你喜欢

转载自blog.csdn.net/Wangguang_/article/details/81046375