#include <iostream>
#define Maxsize 100
#define OK 1
#define ERROR 0
#define OVERFLOW -2
using namespace std;
typedef char ElemType;
typedef int Status;
typedef struct
{
ElemType *elem;//存盤空間的基地址
int length;//當前長度
}SqList;
Status InitList(SqList &L)//初始化順序表
{
L.elem=new ElemType[Maxsize];
if(!L.elem) exit(OVERFLOW); //存盤分配失敗
L.length=0;
return OK;
}
void InsertList(SqList &L)//向順序表中插入元素
{
int i, num;
cout<<"(2)依次在順序表L中插入元素a,b,c,e:"<<endl;
cin>>num;
L.length=num;
for (i = 1; i<=num; i++)
cin >> L.elem[i];
}
void PrintList(SqList L)//輸出順序表L
{
int i;
for (i = 1; i <= L.length; i++)
cout << L.elem[i] << " ";
cout<<endl;
}
void LengthList(SqList L)//輸出順序表的長度
{
cout << "(4)順序表的長度為:" << L.length<<endl;
}
void SearchList(SqList L)//查詢順序表L的第i個元素
{
int i;
cout << "(5)請輸入要查詢元素的位置:";
cin >> i;
cout << "(5)您查詢的元素為:" << L.elem[i] << endl;
}
int LocateElem(SqList L,ElemType e) //輸出元素a的位置
{
for(int i=1;i<L.length;i++)
if(L.elem[i]==e)
cout<<"(6)元素a的位置是:"<<i<<endl;
return 0;
}
Status ListInsert(SqList &L,int i,ElemType e) //在第i個元素之前插入元素f
{
if((i<1)||(i>L.length+1)||(L.length==Maxsize)) return ERROR;
for(int j=L.length+1;j>i;j--)
L.elem[j]=L.elem[j-1];
L.elem[i]=e;
++L.length;
return OK;
}
Status ListDelete(SqList &L,int i)//洗掉第i個元素
{
if((i<1)||(i>L.length)) return ERROR;
for (int j=i;j<=L.length;j++)
L.elem[j] = L.elem[j+1];
--L.length;
return 0;
}
int main()
{
SqList L;
cout<<"(1)初始化順序表L: "<<endl;
InitList(L);
InsertList(L);
cout<<"(3)輸出順序表L: ";
PrintList(L);
LengthList(L);
SearchList(L);
LocateElem(L,'a');
ListInsert(L,4,'f');
cout<<"(7)(8)插入元素f后輸出順序表L: ";
PrintList(L);
ListDelete(L,3);
cout<<"(9)(10)洗掉第3個元素后輸出順序表L: ";
PrintList(L);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/12518.html
標籤:基礎類
上一篇:c++程式編譯錯誤,g++ -Wl,rpath 錯誤
下一篇:一個關于malloc函式位置問題
