数据结构——线性表的链式表示与实现

使用单向链表(增加,删除,查询,修改)

代码如下:

#include "pch.h"
#include<string>
#include <iostream>

using namespace std;

struct LNode
{
	int data;// 数据域
	LNode *next; // 指针域
};


//新建链表
void NewList(LNode *L, int lenght)
{
	int v;					//储存数据域
	LNode *p;
	L->next = NULL;


	for (int i = lenght; i > 0; i--)
	{
		//L = new LNode;				//c++申请空间
		LNode *p = new LNode();
		//p = (LNode*)malloc(sizeof(LNode));		//c申请空间
		cin >> v;
		p->data = v;
		p->next = L->next;
		L->next = p;
	}
}

//查找线性表指定位置的元素值
int GetElem_L(LNode* L, int i, int e)
{
	LNode *p;
	p = L->next;
	int j = 1; 				//初始化
	while (p&&j < i)		//向后扫描,直到p指向第i个元素或p为空 
	{
		p = p->next;
		++j;
	}
	if (!p || j > i)
	{
		return 0;			//第i个元素不存在 
	}
	e = p->data; 			//取第i个元素 
	return 1;
}

//在链表中指定位置插入元素
int ListInsert_L(LNode *L, int i, int e)
{
	LNode* p = L;
	int j = 0;
	while (p&&j < (i - 1))//寻找第i−1个结点		
	{
		p = p->next; ++j;
	}
	if (!p || j > (i - 1))
	{
		return 0;		//i大于表长 + 1或者小于1  
	}
	LNode* s = new LNode;				//生成新结点s 
	s->data = e;      		           	//将结点s的数据域置为e 
	s->next = p->next;	   	          	//将结点s插入L中 
	p->next = s;
	return 1;
}

//将线性表L中第i个数据元素删除
int ListDelete_L(LNode *L, int i, int e)
{
	LNode* p = L;
	int j = 0;
	while (p->next &&j < i - 1)		//寻找第i个结点,并令p指向其前驱 
	{
		p = p->next;
		++j;
	}
	if (!(p->next) || j > i - 1)
	{
		return 0; 					//删除位置不合理 
	}
	LNode *q = p->next; 			//临时保存被删结点的地址以备释放 
	p->next = q->next; 				//改变删除结点前驱结点的指针域 
	e = q->data; 					//保存删除结点的数据域 
	delete q; 						//释放删除结点的空间 
	return 1;
}

//显示链表中的节点元素
int PrintNode(LNode *L)
{
	LNode *p;
	p = L->next;
	if (p == NULL)
	{
		cout << "链表为空!" << endl;
	}
	cout << "链表元素为:";
	while (p != NULL)
	{
		cout << p->data << "  ";
		p = p->next;
	}
	cout << endl;
	return 1;
}

int main()
{
	LNode L;
	int a, m, s;
	//建立
	cout << "请输入链表长度:";
	cin >> a;
	cout << "请输入" << a << "个节点的数据" << endl;
	NewList(&L, a);
	PrintNode(&L);
	//插入
	cout << "请输入所要插入的位置以及数据:";
	cin >> m>>s;
	ListInsert_L(&L, m, s);
	PrintNode(&L);
	//删除
	cout << "请输入所要删除的位置以及数据:";
	cin >> m >> s;
	ListDelete_L(&L,m,s);
	PrintNode(&L);
	//查找
	cout << "请输入所要查找的位置以及数据:";
	cin >> m >> s;
	if (ListInsert_L(&L, m, s))
	{
		cout << "该元素存在!" << endl;
	}
	else
	{
		cout << "该元素不存在!" << endl;
	}

	return 0;
}

结果为:
在这里插入图片描述

发布了35 篇原创文章 · 获赞 27 · 访问量 969

猜你喜欢

转载自blog.csdn.net/weixin_45525272/article/details/104301446
今日推荐