ITPub博客

首页 > 架构设计 > > 数据结构与算法实现代码(1)——顺序表

数据结构与算法实现代码(1)——顺序表

作者:浪花小雨滴 时间:2020-05-20 11:59:32 0 删除 编辑

本系列文章将更新一些数据结构和算法的实战代码(包括Python和C++),后期将有LeetCode习题等。

我们建立一个头文件用于建立结构体与函数等。

首先写上预备代码。。。

#include<iostream>
#include<string.h>
using namespace std;

然后建立线性表。

struct List  //用结构体建立顺序表,如果对象包含多个特征,可以另外建立结构体替代char
{
	char data[50];
	int length;
};

接下来是几个基础操作的函数。

void initList(List *&l)//初始化一个空表
 {
	 l = (List*)malloc(sizeof(List));
	 l->length = ;
 }


void createList(List *&l,char ass[]) //用ass中的数据给线性表赋值
{
	l = (List*)malloc(sizeof(List));
	int i,n;
	n = strlen(ass) / sizeof(ass[]);
	l->length = n;
	for(i=;i<n;i++)
		l->data[i] = ass[i];
}


void destroyList(List*& l) //销毁线性表
{
	free(l);
}


bool emptyList(List*& l)  //确定线性表是否为空
{
	return (l->length == );
}


int lengthList(List*& l)  //求线性表的长度
{
	return (l->length);
}


void coutList(List*& l)  //依次输出线性表所有元素
{
	int i;
	for (i = ;i < l->length;i++)
		cout << l->data[i];
}


void getiList(char& e,int i,List*& l)//获取第i个元素
{
	if (i > l->length)
		cout << "超出顺序表范围";
	else
		e = l->data[i-1];
}


int findeList(char e, List*& l)//找到第一个元素e所在的位置
{
	int i = ;
	while (l->data[i] != e&&i<l->length)
	{
		i++;
	}
	if (i < l->length)
		return (i + 1);
	else
		cout << "未找到元素";
		return ;
}


void insertList(char e, int i, List*& l)  //将e插入第i个位置
{
	if (i<1 || i>l->length + 1)
		cout << "超出范围";
	else
	{
		int j = l->length;
		for (j;j >=i;j--)
			l->data[j] = l->data[j - 1];
		l->data[i - 1] = e;
		l->length = l->length + 1;
	}
}


void deleteList(int i, List*& l)//删除第i个元素
{
	if (i<1 || i>l->length)
		cout << "超出范围";
	else
	{
		int j = i - 1;
		for (j;j <l->length-1;j++)
			l->data[j] = l->data[j + 1];
		l->data[l->length - 1] = '\0';
		l->length = l->length - 1;
	}
}

下面给出测试代码。

#include<iostream>
#include<math.h>
#include<string.h>
#include"shunxubiao.h"
using namespace std;
int main()
{
	char x='5',a[27] = "abcdefghijklmnopqrstuvwxyz";
	List* list;
	initList(list);
	cout << list->length<<endl;
	createList(list,a);
	cout << list->length << endl << list->data[1]<<endl;
	cout << emptyList(list)<<endl;
	coutList(list);
	cout << endl << lengthList(list) << endl;
	int n=3;
	getiList(x, n, list);
	cout << x<<endl;
	cout << findeList('b', list)<<endl;
	insertList('a', 2, list);
	cout << list->length << endl << list->data[1];
	deleteList(2, list);
	cout << list->length << endl << list->data[1];
	destroyList(list);
}


下一篇

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/31537575/viewspace-3129999/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2018-05-16

  • 博文量
    4259
  • 访问量
    46333