c++实现顺序表的基本功能

 

#include <iostream>
#include <vector>
using namespace std;


struct Line{
	int names[20];
	int length;
};

Line* InitList(){
	Line *L = new Line;
	L->length = 10;
	for (int i=0; i<10; i++){
		L->names[i] = i;
	}
	return L;
}

void DestoryList(Line* L){
	cout << "delete line success" << endl;
	delete L;
}

int ListLength(Line* L){
	int n = L->length;
	return n;
}

//根据索引查找值
int GetIndex(Line* L, int index){
	int n = L->length;
	int ret = -1;
	for (int i=0; i<n; i++){
		if (index==i)
			ret = L->names[i];
	}
	return ret;
}

//根据值查找索引
int GetValue(Line* &L, int key){
	int index = -1;
	int n = L->length;
	for (int i=0; i<n; i++){
		if (L->names[i]==key)
			index = i;
	}
	return index;
}

void InsertList(Line* &L, int index, int value){
	int n = L->length;
	if (index<0 || index>n)
		cout << "this index is wrong" << endl;
	for (int i=n; i>index; i--){
		L->names[i] = L->names[i-1];//表中所有的值后移一位
	}
	L->names[index] = value;
	L->length++;
}

void DeleteList(Line* &L, int index){
	int n = L->length;
	if (index<0 || index>n)
		cout << "this index is wrong " << index << endl;
	for (int i=index; i<n; i++){
		L->names[i] = L->names[i+1];//值往前移
	}
	L->length--;
}

void ShowList(Line* L){
	int n = L->length;
	for (int i=0; i<n; i++){
		cout << L->names[i] << "\t";
	}
	cout << endl;
}

bool IsEmpty(Line* L){
	return (L->length == 0);
}

//删除表中所有为value的值
void DeleteValue(Line* &L, int value){
	int n = L->length;
	int i = 0, k=0;
	while (i<n){
		if (L->names[i] == value){
			k++;//记录value出现的次数
		}else{
			L->names[i-k] = L->names[i];//值往前移k位
		}
		i++;
	}
	L->length -= k;
}

void swap(int& a, int& b){
	int temp = a;
	a = b;
	b = temp;
}
void showlist(vector<int> nums){
	for (int i=0; i<nums.size(); i++){
		cout << nums[i] << "\t";
	}
	cout << endl;
}

int main(){
	Line* L = new Line;
	L = InitList();
	ShowList(L);
	InsertList(L, 2, 5);
	ShowList(L);
	DeleteValue(L, 5);
	ShowList(L);
	movel(L, 0, L->length);
	DeleteList(L, 7);
	ShowList(L);
	int index_value = GetValue(L, 3);
	cout << "this value index is "  << index_value << endl;
	int index = GetIndex(L, 3);
	cout << "this index value is " << index << endl;
	int length = ListLength(L);
	cout << "this list length is " << length << endl;
	bool before_empty = IsEmpty(L);
	cout << "is empty: " << before_empty << endl;
	for (int i=9; i>=0; i--){
		DeleteList(L, i);
	}
	int length_a = ListLength(L);
	cout << "this list length is " << length_a << " after delete!" << endl;
	bool empty = IsEmpty(L);
	cout << "is empty after delete: " << empty << endl;
	DestoryList(L);
	return 0;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值