顺序表相关基本操作(从文件中读取数据)

顺序表的基本操作

  1. 初始化表
  2. 建表
  3. 增加元素
  4. 删除元素
  5. 遍历
  6. 唯一化顺序表

头文件:

#ifndef _SQLIST_H_
#define _SQLIST_H_

#include <iostream>
#include <fstream>
using namespace std;
#define OK 1
#define ERROR 0
#define OVERFLOW -1
#define MAXSIZE 100

typedef int Status;
typedef int KeyType;

typedef struct
{
	KeyType key;
}Data;

typedef struct
{
	Data *r;  //结点数据
	int lenth;  //顺序表长度
	int listsize;  //最大长度
}SqList;

Status initSqList(SqList &L)
{
	L.r = (Data *)malloc((MAXSIZE + 1) * sizeof(Data)); //含哨兵
	if (!L.r)
		exit (OVERFLOW);
	L.lenth = 0;
	L.listsize = MAXSIZE + 1;
	return OK;
}

Status CreateSqList(SqList &L)
{
	fstream file;
	file.open("data.txt",ios::in);
	if (!file)
	{
		cout<<"文件打开失败...\n";
		return ERROR;
	}
	int i = 1;
	while (!file.eof())
	{
		file >> L.r[i].key;
		i++;
		L.lenth++;
	}
}

void Visit(SqList L)
{	
	cout << "遍历:";
	for (int i = 1; i <= L.lenth; i++)
		cout << L.r[i].key << " ";
	cout << endl;
}

Status InsertElem(SqList &L, int n, Data e)
{
	if (n < 1 && n > L.lenth)
	{
		cout << "插入位置不合法" << endl;
		return ERROR;
	}
	if (++L.lenth > L.listsize)
	{
		cout << "空间不足" << endl;
		return OVERFLOW;
	}
	for (int i = L.lenth - 1; i >= n; i--)
		L.r[i + 1] = L.r[i];
	L.r[n] = e;
	return OK;
}

Status deleteElem(SqList &L,KeyType e)
{
	for (int i = 1; i <= L.lenth; i++)
	{
		if (L.r[i].key == e)
		{	
			for(int j = i; j < L.lenth; j++)
				L.r[j] = L.r[j + 1];
			--L.lenth;
			return OK;
		}
	}
	cout << "不存在该元素" << endl;
	return ERROR;
}

Status updateElem(SqList &L,KeyType e,Data d)
{
	for (int i = 1; i <= L.lenth; i++)
	{
		if (L.r[i].key == e)
		{	
			L.r[i] = d;
			return OK;
		}
	}
	cout << "不存在该元素" << endl;
	return ERROR;
}

void Unique(SqList &L)
{
	for (int i = 1; i < L.lenth; i++)
	{
		for(int j = i + 1; j <= L.lenth; )
		{
			if(L.r[i].key == L.r[j].key)
			{	
				for (int k = j; k < L.lenth; k++)
					L.r[k] = L.r[k + 1];
				L.lenth--;
			}
			else
				j++;
		}
	}
}



#endif  
发布了16 篇原创文章 · 获赞 25 · 访问量 1142

猜你喜欢

转载自blog.csdn.net/weixin_41546300/article/details/104649244