#include<iostream>
#include"cstdlib"
#include<string>
using namespace std;
//定义结构体类型
struct SeqList{
int MAXNUM;
int n;
int *element;
};
typedef struct SeqList *PSeqList;
//创建空的循序链表
PSeqList createNullList_seq(int m);
//判断链表是否为空
int isNullList_seq(PSeqList palist) ;
//求元素的下标
int locate_seq(PSeqList palist, int x);
//顺序表的插入
int insertPre_seq(PSeqList palist,int p, int x);
//删除元素
int deleteP_seq(PSeqList palist, int p);
// 打印顺序表中的元素
void printSeqList(PSeqList palist);
PSeqList createNullList_seq(int m)
{
PSeqList palist=(PSeqList) malloc(sizeof(SeqList));
if(palist!=NULL)
{
palist->element=(int *) malloc(sizeof(int)*m);
if(palist->element)
{
palist->MAXNUM=m;
palist->n=0;
return palist;
}
else free(palist);
}
cout<<" out of space "<<endl;
return NULL;
}
int isNullList_seq(PSeqList palist)
{
if(palist->n==0)
return 1;
return 0;
}
int locate_seq(PSeqList palist, int x)
{
for(int i=0; i<palist->n; i++)
{
if(palist->element[i]==x)
return i;
else
return -1;
}
}
//在palist所指顺序表下标为p的元素插入x
int insertPre_seq(PSeqList palist,int p, int x)
{
int q;
if(palist->n>=palist->MAXNUM)
{
cout<<" overflow "<<endl;
return 0;
}
if(p<0||p>palist->n)
{
cout<<" not exist locate"<<endl;
return 0;
}
/*
for(q=p; q<palist->n; q++)
移动元素只能从后到前面,注意bug
*/
for(q=palist->n-1; q>=p; q--)
{
palist->element[q+1]=palist->element[q];
}
palist->element[p]=x;
palist->n=palist->n+1;
return 1;
}
int deleteP_seq(PSeqList palist, int p)
{
if(p<0||p>palist->n-1)
{
cout<<" not exist"<<endl;
return 0;
}
for(int i=p; i<palist->n-1; i++)
{
palist->element[i]=palist->element[i+1];
}
palist->n=palist->n-1;
return 1;
}
void printSeqList(PSeqList palist)
{
if(palist->n==0)
cout<<" 没有元素"<<endl;
for(int i=0; i<palist->n; i++)
cout<<" "<<palist->element[i];
}
int main()
{
PSeqList p=createNullList_seq(100);
int tag=isNullList_seq(p);
if(tag)
cout<<"-------- 是空链表"<<endl;
else
cout<<"-------- 不是空链表"<<endl;
for(int i=1; i<9; i++)
{
insertPre_seq(p,0,i);
cout<<"---"<<i<<endl;
}
printSeqList(p);
return 0;
}
结果
-------- 是空链表
---1
---2
---3
---4
---5
---6
---7
---8
8 7 6 5 4 3 2 1
--------------------------------
Process exited after 0.03496 seconds with return value 0
请按任意键继续. . .
网友评论