关于顺序表的插入,查询,删除,清空,非递归归并排序,递归归并排序,位移法删除重复元素,查找法删除重复元素等等基本操作代码,以及关于malloc的动态分配内存的解释,重要解释在代码中:
#include<bits/stdc++.h>
using namespace std;
#define MAXSIZE 200000
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define INFEASIBLE -1
#define OVERFLOW -2
typedef int ElemType;
typedef int Status;
typedef struct{
ElemType *elem;
int length;
}SqList;
Status InitList(SqList &L){
L.elem=(ElemType *)malloc(MAXSIZE*sizeof(ElemType));
L.length=0;
if(L.elem==NULL) return ERROR;
return OK;
}
void DestroyList(SqList &L){
if(L.elem) delete L.elem;
}
void ClearList(SqList &L){ L.length=0;}
int ListEmpty(SqList L){if(L.length==0) return 1;return 0;}
int ListLength(SqList L){return L.length;}
int GetElem(SqList L,int i,ElemType &e){
if(i<1||i>L.length) return ERROR;
e=L.elem[i-1];
return OK;
}
int LocateElem(SqList L,ElemType e){
for(int i=1;i<=L.length;i++){
if(L.elem[i-1]==e) return i;
}
return 0;
}
int PriorElem();
int NextElem();
Status ListInsert(SqList &L,int i,ElemType e){
if(i<1||i>L.length+1) return ERROR;
if(L.length>=MAXSIZE) return ERROR;
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 OK;
}
Status ListDelete(SqList &L,int i){
if(i<1||i>L.length) return ERROR;
for(int j=i;j<=L.length-1;j++){
L.elem[j-1]=L.elem[j];
}
L.length--;
return OK;
}
void ListTravel(SqList &L){
for(int i=1;i<=L.length;i++){
if(i==1) cout<<L.elem[i-1];
else cout<<" "<<L.elem[i-1];
}
return ;
}
SqList Merge_Sort(SqList L1,SqList L2){
SqList L;
InitList(L);
int i=1,j=1;
while(i<=L1.length&&j<=L2.length){
if(L1.elem[i-1]<L2.elem[j-1]) ListInsert(L,L.length+1,L1.elem[i-1]),i++;
else ListInsert(L,L.length+1,L2.elem[j-1]),j++;
}
while(i<=L1.length) ListInsert(L,L.length+1,L1.elem[i-1]),i++;
while(j<=L2.length) ListInsert(L,L.length+1,L2.elem[j-1]),j++;
return L;
}
Status ListFind(SqList L,ElemType x){
for(int i=1;i<=L.length;i++){
if(L.elem[i-1]==x) return OK;
}
return ERROR;
}
void ListInsertOnlyOne(SqList &L,ElemType x){
if(!ListFind(L,x)) ListInsert(L,L.length+1,x);
}
int ListFindSecondPos(SqList &L){
for(int i=0;i<L.length-1;i++){
for(int j=i+1;j<L.length;j++){
if(L.elem[i]==L.elem[j]){
for(int k=j;k<=L.length-2;k++){
L.elem[k]=L.elem[k+1];
}
L.length--;
j--;
}
}
}
return 0;
}
int main(){
int n;
cin>>n;
while(n--){
SqList L;
InitList(L);
int m;
cin>>m;
for(int i=1;i<=m;i++){
int x;cin>>x;
ListInsert(L,i,x);
}
ListFindSecondPos(L);
ListTravel(L);
if(n) cout<<endl;
}
return 0;
}
|