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

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

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

#include<bits/stdc++.h>
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;
}

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值