聲明:
#include <stdio.h>
#include "stdlib.h"
typedef int DataType;
1.構造一個機構體
//創建空順序表
PSeqList createNullList_seq(int m)
{
PSeqList palist=(PSeqList)malloc(sizeof(struct SeqList));
if (palist!=NULL)
{
palist->element=(DataType *)malloc(sizeof(DataType) * m);
if(palist->element)
{
palist->MAXNUM=m;
palist->n=0;
return palist;
}
else
{
free(palist);
}
}
printf("out of space!! \n");
return NULL;
}
2.
//判斷palist所指順序表是不是為空表
int isNullList_Seq(PSeqList palist)
{
return (palist->n==0);
}
3.
//在palist所指順序表中尋找第一個值為X的元素下標
int locate_seq(PSeqList palist,DataType x)
{
int q;
for(q=0;q<palist->n;q++)
{
if (palist->element[q]==x) {
return q;
}
}
return -1;
}
4.
//順序表的插入,在palist所指順序表中下標為p的元素之前插入元素x
int insertPre_seq(PSeqList palist,int p,DataType x)
{
DataType * pos1;
int q;
if(palist->n>=palist->MAXNUM)
{
//順序表空間的擴展 www.2cto.com
pos1=(DataType*)malloc(sizeof(DataType)*palist->MAXNUM*2);
if(pos1==NULL)
{
printf("Overflow!");
return 0;
}
for(q=0;q<palist->MAXNUM;q++)
{
pos1[q]=palist->element[q];
}
free(palist->element);
palist->element=pos1;
palist->MAXNUM*=2;
}
if (p<0||p>palist->n) {
printf("Not Exist!! \n");
return 0;
}
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;
}
5.
//順序表的插入,在palist所指順序表中下標為p的元素之後插入元素x
int insertPost_seq(PSeqList palist,int p,DataType x)
{
int q;
if(palist->n>=palist->MAXNUM)
{
printf("OverFlow \n");
return 0;
}
if (p<0||p>palist->n) {
printf("Not Exist!! \n");
return 0;
}
for(q=palist->n-1;q>=p+1;q--)
{
palist->element[q+1]=palist->element[q];
}
palist->element[p+1]=x;
palist->n=palist->n+1;
return 1;
}
6.
//順序表的刪除,在palist所指順序表中刪除下標為p的元素
int deleteP_seq(PSeqList palist,int p)
{
int q;
if (q<0||q>palist->n-1)
{
printf("Not Exist!! \n");
return 0;
}
for(q=p;q<palist->n-1;q++)
{
palist->element[q]=palist->element[q+1];
}
palist->n=palist->n-1;
return 1;
}
7.
int deleteV_seq(PSeqList palist,DataType x)
{
int q=locate_seq(palist,x);
deleteP_seq(palist,q);
return 1;
}
8.
測試
int main()
{
int i;
PSeqList list1= createNullList_seq(50);
insertPre_seq(list1,0,12);
insertPre_seq(list1,1,22);
insertPre_seq(list1,2,32);
insertPost_seq(list1,3,43);
insertPost_seq(list1,3,53);
insertPost_seq(list1,4,63);
insertPost_seq(list1,1,73);
i=locate_seq(list1,73);
printf("%d",i);
return 1;
}
摘自 yucong