C++数据结构——线性表的顺序表示和实现

#include <iostream>
#include <cstring>
using namespace std;
#define MAXSIZE 10000 

struct Book{
	string no;
	string name;
	float price;
	Book(){};
	Book(string, string, float);
	friend bool operator == (Book &book1,Book &book2);//友元函数,重载单目运算符“==”
};

bool operator == (Book &book1,Book &book2){
//	book1.no.compare(book2.no)&&book1.name.compare(book2.name)&&(book1.price==book2.price)
	if(book1.no.compare(book2.no)){
		if(book1.name.compare(book2.name)){
			if(book1.price == book2.price){
				return true;
			}
		}
	}
	else return false;
}
Book::Book(string n, string na, float pr){
	no = n;
	name = na;
	price = pr;
}

struct SqList{
	Book *elem;
	int length;
};

bool InitList(SqList &L){
	L.elem = new Book[MAXSIZE];
	if(!L.elem)
		return false;
	L.length=0;
	return true;
}

bool ListInsert(SqList &L,int i, Book e){
	if((i<1)||(i>L.length+1))return false;
	if(L.length==MAXSIZE)return false;
	
	for(int j=L.length-1;j>=i-1;j--){
		L.elem[j+1]=L.elem[j];
	}
	L.elem[i-1]=e;
	++L.length;
	return true;
}

bool GetElem(SqList L,int i, Book &e){
	if(i<1||i>L.length)return false;
	e = L.elem[i-1];
	return true;
}


int LocaleElem(SqList L,Book e){
	for(int i=0;i<L.length;i++){
		if(L.elem[i]==e) return i+1;//使用重载之后的运算符判断两个结构体实例是否相等
	}
	return 0;
}

bool ListDelete(SqList &L, int i){
	if((i<1)||(i>L.length+1))return false;
	for(int j=i;j<=L.length-1;j++){
		L.elem[j-1] = L.elem[j];
	}
	--L.length;
	return true;
}
void showList(SqList sq){
	for(int i=0;i<sq.length;i++){
		cout<<sq.elem[i].no<<"\t"<<sq.elem[i].name<<"\t"<<sq.elem[i].price<<endl;
	}
}

int main(){
	
	SqList sq;
	InitList(sq);
	Book book("001","数据结构",35.00);
	Book book1("002","C++程序设计",35.00);
	cout << "begin" << endl;
	ListInsert(sq,1,book);
	ListInsert(sq,2,book1);
	
//	cout<<"length:"<<sq.length<<endl;
//	获取元素 
	/*
	Book book2;
	GetElem(sq,1,book2);
	cout << book2.name << endl;
	*/
//	查找位置 
	/* 
	cout<<"index:"<<LocaleElem(sq,book1) << endl;
	*/ 
//	Book book2("001","数据结构",35.00);
//	cout << (book==book2)<<endl;
//	删除线性表数据
	cout<<"删除之前"<<endl;
	showList(sq);
	cout<<ListDelete(sq,1)<<endl;
	cout<<"删除之后"<<endl;
	showList(sq);

	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值