欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

数据结构 顺序表的插入、删除与查找基本操作

程序员文章站 2022-03-22 19:55:34
...
#include<iostream>
#include<string>

#define MAXSIZE 100  //存储空间初始分配量 
#define OK 1
#define ERROR 0
#define TRUE 1
#define FALSE 0
using namespace std;

typedef struct {
	int data[MAXSIZE];
	string str[MAXSIZE];
	int length=0;
}SqList;

int GetElem(SqList L,int i)
{
	if(L.length==0||i<1||i>L.length)
		return ERROR;
	cout << L.str[i] << "  " << L.data[i] << endl;
	return OK;	
} 

int ListInsert(SqList *L,int i)
{
	int k,e;
	string str;
	cout << "Please input e & str : ";
	cin >> str;
	cin >> e;
	if(L->length==MAXSIZE)		//线性表已满 
		return ERROR;
	if(i<1||i>L->length+1)      //当i不在范围中
		return ERROR;
	if(i<=L->length)				//当i在中间 
	{
		for(k=L->length-1;k>=i-1;k--)
			//所有数据往后挪一位
			{
				L->data[k+1]=L->data[k];
				L->str[k+1]=L->str[k];
			}
	}
	L->data[i-1]=e;
	L->str[i-1]=str;
	L->length++;
	return OK;
}

int ListDelete(SqList *L,int i)
{
	int k;
	if(L->length==0)
		return ERROR;
	if(i<1||i>L->length+1)
		return ERROR;
	if(i<=L->length)
	{
		for(k=i;k<L->length+1;k++)
		{
			L->data[k-1]=L->data[k];
			L->str[k-1]=L->str[k];
		}	
			
	}
	L->length--;
	return OK;
}

int main()
{
	SqList L;
	int i;
	int k;
	int m;
		
	//插入 
	cin >> m;
	for(int i=1;i<=m;i++)
	{
		ListInsert(&L,i);
	}

	cout << "This is List's Find operation !\n";
	do
	{
		cout << "Please input i(if i==0 break while) :";
		cin >> i;
		if(i==0) break;
		if(!GetElem(L,i))
			cout << "Not found\n";	
	}while(i);
	
	//删除操作
	cout << "This is List's Delete operation !\n";
	do
	{
		cout << "Please input you want delete's postion :";
		cin >> i;
		if(i==0) break;
		if(ListDelete(&L,i))
			cout << "YES\n";
		else 
			cout << "No\n";
	}while(i);	
	
	for(int i=0;i<L.length;i++)
		cout << L.str[i] << " " << L.data[i] << "   ";
	cout << endl;
	
	return 0;
}