数据结构之单链表

链表是线性表的链式存储方式,逻辑上相邻的数据在计算机内的存储位置不必相邻。
链表插入,删除数据效率比顺序表高

//开发工具:vs2019
//图形库:EasyX_2019
//qq:1020785391
//作者:WJ
#include <iostream>

using namespace std;

//链表结构体定义
typedef struct _LinkList
{
	int data;
	struct _LinkList* next;
}LinkList, ListNode;

//初始化
bool initList(LinkList*& L)
{
	L = new ListNode;
	if (!L) return false;
	L->data = -1;
	L->next = NULL;
	return true;
}

//前插法
bool listInsert_front(LinkList*& L, ListNode* node)
{
	if (!L || !node) return false;
	node->next = L->next;
	L->next = node;
	return true;
}

//输出
void listPrint(LinkList* &L)
{
	ListNode* p=NULL;
	if (!L)
	{
		cout << "链表为空链表" << endl;
		return;
	}
	p = L->next;
	while (p)
	{
		cout << p->data << "\t";
		p = p->next;
	}
	cout << endl;
}

bool listInsert_back(LinkList*& L, ListNode* node)
{
	if (!L || !node) return false;
	ListNode* last;
	last = L;
	while (last->next) last = last->next;
	node->next = last->next;
	last->next = node;
	return true;
}

//指定位置插入
bool listInsert(LinkList*& L, int i, int& e)
{
	if (!L) return false;
	ListNode* p, * s;
	int j = 0;
	p = L;
	while (p && j < i - 1)
	{
		p = p->next;
		j++;
	}
	if (!p || j > i - 1) return false;
	s = new ListNode;
	s->data = e;
	s->next = p->next;
	p->next = s;
	return true;
}

//查找指定位置元素
bool List_GetElem(LinkList*& L, int i, int& e)
{
	if (!L) return false;
	int index = 0;
	ListNode* p;
	p = L;
	while (p && index < i)
	{
		p = p->next;
		index++;
	}
	if (!p || index > 1) return false;
	e = p->data;
	return true;
}

//按值查找
bool List_FindElem(LinkList*& L, int e)
{
	if (!L || !L->next) return false;
	ListNode* p;
	p = L->next;
	while (p)
	{
		if (p->data == e) return true;
		p = p->next;
	}
	return false;
}

//按位置,删除元素
bool listDelete(LinkList* &L, int i)
{
	ListNode *p, *q;
	int j = 0;
	p = L;
	while (p->next && j < i - 1)
	{
		p = p->next;
		j++;
	}
	if (!p->next || j > i - 1) return false;
	q = p->next;
	p->next = q->next;
	delete q;
	return true;
}

//销毁链表
void listDestroy(LinkList*& L)
{
	ListNode* p;
	p = L;
	while (p)
	{
		L = L->next;
		delete p;
		p = L;
	}
}

int main()
{
	LinkList* L;
	ListNode* node;
	if (initList(L)) cout << "初始化成功" << endl;
	else cout << "初始化失败" << endl;


	for (int i = 0; i < 5; i++)
	{
		node = new ListNode;
		node->data = i;
		node->next = NULL;
		if (listInsert_front(L, node)) cout << "添加成功" << endl;
		else cout << "添加失败" << endl;
	}
	listPrint(L);
	if (List_FindElem(L, 2)) cout << "2存在" << endl;
	else cout << "2不存在" << endl;
	 
	int e;
	List_GetElem(L, 1, e);
	cout << "1位置的元素是:" << e << endl;

	listDelete(L, 3);
	listPrint(L);
	listDestroy(L);
	listPrint(L);
	system("pause");
	return 0;
}

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值