栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

带头结点的单链表的基本操作

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

带头结点的单链表的基本操作

首先,对于单链表来说,带头结点比不带头结点的好处是很大的,体现在对其的基本操作中,

这里,特别说明下,头结点可以看做是一个标志,并没有具体的数值;

#include
using namespace std;
typedef struct LNode
{
	int data;
	struct LNode* next;
}LNode,*Linklist;   //LNode*强调这是一个结点,Linklist强调这是一个链表,两者本质上是一样的

//初始化
void Initlist(Linklist& L)
{
	L = (LNode*)malloc(sizeof(LNode));
	if (L == NULL)
		cout << "内存不足,分配失败!" << endl;
	L->next = NULL;
	cout << "初始化成功!" << endl;
}

void EmptyIf(Linklist L)
{
	if (L->next == NULL)
		cout << "链表为空!" << endl;
	else
		cout << "链表不为空!" << endl;
}

void Insertlist(Linklist L, int location, int e)
{
	if (location < 1)
		cout << "插入位置越界!" << endl;
	LNode* p;
	int i = 0; //i为第i个位置,这里将头结点看作第0个位置
	p = L;
	while (p != NULL && i < location - 1) //循环作用,p指针指向第(location-1)的位置
	{
		p = p->next;
		i++;
	}
	if (p == NULL)
		cout << "插入位置不合法!" << endl;
	LNode* s = (LNode*)malloc(sizeof(LNode)); //创建新结点,即为要插入的结点
	s->data = e;
	s->next = p->next;
	p->next = s;
	cout << "插入成功!" << endl;
}

Linklist HeadInsertlist(Linklist L) //头插法
{
	int x = 0;
	cin >> x;
	while (x != 999)
	{
		LNode* s = (LNode*)malloc(sizeof(LNode));
		s->data = x;
		s->next = L->next;
		L->next = s;
		cin >> x;
	}
	return L;
}

Linklist NextInsertlist(Linklist& L) //尾插法
{
	int x = 0;
	LNode* r = L;//尾结点
	cin >> x;
	while (x != 999)
	{
		LNode* s = (LNode*)malloc(sizeof(LNode));
		s->data = x;
		s->next = r->next;
		r->next = s;
		r = s;
		cin >> x;
	}
	r->next = NULL;
	return L;
}

void Printlist(Linklist L)
{
	LNode* p;
	p = L;
	if (p->next == NULL)
		cout << "链表为空!" << endl;
	else
	{
		p = p->next;
		while (p != NULL)
		{
			cout << p->data << " ";
			p = p->next;
		}
	}
}

int main()
{
	Linklist L;
	Initlist(L);
	//HeadInsertlist(L);
	NextInsertlist(L);
	//EmptyIf(L);
	//Insertlist(L, 1, 1);
	//Insertlist(L, 2, 2);
	//Insertlist(L, 3, 3);
	Printlist(L);
	return 0;
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/832517.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号