顺序表
这里是头文件
#ifndef _SEQLIST_H
#define _SEQLIST_H
#include"Utili.h"
#include<assert.h>
#define ElemType int
#define SEQLIST_DEFAULT_SIZE 8
typedef struct SeqList
{
ElemType *base;
size_t capacity;
size_t len;
}SeqList;
void InitSeqList(SeqList* list);
bool push_back(SeqList *list,ElemType x);
bool show_list(SeqList *list);
bool push_front(SeqList *list,ElemType x);
bool insert_pos(SeqList *list,int pos,ElemType x);
void InitSeqList(SeqList *list){
list->base = (ElemType*)malloc(sizeof(ElemType)*SEQLIST_DEFAULT_SIZE);
assert(list->base != NULL);
list->capacity = SEQLIST_DEFAULT_SIZE;
list->len=0;
}
bool push_back(SeqList *list,ElemType x){
if(list->len >= list->capacity){
cout<<"空间已经满了"<<x<<"不能尾部插入 "<<endl;
return false;
}
list->base[list->len]=x;
list->len++;
return true;
}
bool show_list(SeqList *list){
for(int i=0;i<(list->len);i++){
cout<<list->base[i]<<" ";
}
cout<<endl;
return true;
}
bool push_front(SeqList *list,ElemType x){
if(list->len >= list->capacity){
cout<<"空间已经满了"<<x<<"不能尾部插入 "<<endl;
return false;
}
for(int i=list->len;i>0;i--){
list->base[i]=list->base[i-1];
}
list->base[0]=x;
list->len++;
return true;
}
size_t Length(SeqList *list){
return list->len;
}
bool insert_pos(SeqList *list,int pos,ElemType x){
if(list->len >= list->capacity){
cout<<"空间已经满了"<<x<<"不能插入 "<<endl;
return false;
}
if(pos<0 || pos>list->len){
cout<<"插入的位置非法"<<endl;
return false;
}
for(int i=list->len;i>pos;i--){
list->base[i]=list->base[i-1];
}
list->base[pos]=x;
list->len++;
return true;
}
#endif
这里是主函数
#include<iostream>
#include"SeqList.h"
using namespace std;
int main(){
SeqList mylist;
InitSeqList(&mylist);
int select = 1;
ElemType item;
int pos;
while(select){
cout<<"************************************************************"<<endl;
cout<<"*[1]push_back [2]push_front *"<<endl;
cout<<"*[3]show_list [0]quit_system *"<<endl;
cout<<"*[4]pop_back [5]pop_front *"<<endl;
cout<<"*[6]insert_pos [7]insert_val *"<<endl;
cout<<"*[8]delete_pos [9]delete_val *"<<endl;
cout<<"*[10]find_key [11]length *"<<endl;
cout<<"************************************************************"<<endl;
cout<<"请选择:>";
cin>>select;
switch(select){
case 1:
cout<<"请输入要插入的数据(-1结束):>";
while(cin>>item,item!=-1){
push_back(&mylist,item);
}
break;
case 2:
cout<<"请输入要插入的数据(-1结束):>";
while(cin>>item,item!=-1){
push_front(&mylist,item);
}
break;
case 3:
show_list(&mylist);
break;
case 6:
cout<<"请输入要插入的位置:>";
cin>>pos;
cout<<"请输入要插入的值:>";
cin>>item;
insert_pos(&mylist,pos,item);
case 11:
cout<<"SeqList Length = "<<Length(&mylist)<<endl;
break;
case 0:
break;
}
system("pause");
system("cls");
}
return 0;
}