/*main*/
#include<stdio.h>
#include<stdlib.h>
#define TRUE 1
#define ERROR 0
#define OK 1
#define FALSE 0
#define OVERFLOW -2
typedef int status;
typedef int ElemType;
#define LIST_INIT_SIZE 100
#define LISTINCREMENT 10
typedef struct {
ElemType *elem;
int length;
int listsize;
}SqList;
#include"czhs.h"
int main()
{
SqList L,La,Lb;
ElemType x,t=0;
int i,u,y,k;
InitList(L);
InitList(La);
InitList(Lb);
printf("輸入表L長度:");
scanf("%d",&L.length);
printf("向表中輸入元素:");
CreateList(L);
for(int j=0;j<L.length;j++)
printf("%d ",L.elem[j]);
putchar(10);
printf("插入的位置和元素:");
scanf("%d",&i);
scanf("%d",&x);
InsertList(L,i,x);
for(int j=0;j<L.length;j++)
printf("%d ",L.elem[j]);
putchar(10);
printf("刪除元素的位置:");
scanf("%d",&u);
DelateList(L,u,t);
for(int j=0;j<L.length;j++)
printf("%d ",L.elem[j]);
putchar(10);
printf("輸入需查找元素:");
scanf("%d",&y);
FindList(L,y);
printf("輸入要修改元素的位置:");
scanf("%d",&k);
printf("請輸入修改好的元素:");
AlterList(L,k);
for(int j=0;j<L.length;j++)
printf("%d ",L.elem[j]);
putchar(10);
printf("輸入La的長度:");
scanf("%d",&La.length);
printf("向表中輸入元素:");
CreateList(La);
MergeList(L,La,Lb);
for(int j=0;j<Lb.length;j++)
printf("%d ",Lb.elem[j]);
return 0;
}
/*czhs.h*/
status InitList(SqList &L)//&符號千萬不要忘記加
{
L.elem = (ElemType *)malloc(LIST_INIT_SIZE*sizeof(ElemType));
if(!L.elem)exit(OVERFLOW);
L.length=0;
L.listsize=LIST_INIT_SIZE;
return OK;
}
status CreateList(SqList &L)
{
int i;
for(i=0;i<L.length;i++)
{
scanf("%d",&L.elem[i]);
}
return OK;
}
status InsertList(SqList &L,int i,ElemType e)//插入
{
if(i<1||i>L.length+1)
return ERROR;
if(L.length>=L.listsize)
{
L.elem=(ElemType *)realloc(L.elem,
(L.listsize+LISTINCREMENT)*sizeof(ElemType));
if(!L.elem)exit(OVERFLOW);
L.listsize+=LISTINCREMENT;
}
for(int j=L.length-1;j>=i-1;j--)//從最後一個數開始後移一個位置(位置=leng-1),移至i-1位置,i-1的位置爲插入位置
L.elem[j+1]=L.elem[j];
L.elem[i-1]=e;
L.length++;
return OK;
}
status DelateList(SqList &L,int x,ElemType t)//刪除
{
ElemType *q,*p;
if((x<1)||(x>L.length))return ERROR;
p=&(L.elem[x-1]);
t=*p;
q=L.elem+L.length-1;
for(++p;p<=q;++p)*(p-1)=*p;
--L.length;
return OK;
}
status FindList(SqList &L,ElemType y)//查詢與y相等值得元素在表中的位置,用z返回地址;
{
if(L.length==0){
printf("表空!");
return ERROR;
}
for(int i=0;i<L.length;i++)
{
if(L.elem[i]==y)printf("%d\n",i+1);
}
return OK;
}
status AlterList(SqList &L,int i)//修改表中元素;
{
if(i<0||i>L.length-1)return ERROR;
ElemType b;
scanf("%d",&b);
L.elem[i-1]=b;
return OK;
}
status MergeList(SqList &L,SqList &La,SqList &Lb)//按值非遞減合併排列;Lb=La+L;
{
int i,j,p;
i=p=j=0;
if(L.length==0||La.length==0)return ERROR;
while(1)
{
if(L.elem[j]<=La.elem[p])
{
if(j>=L.length)
break;
Lb.elem[i]=L.elem[j];
i++;
Lb.length++;
j++;
}
else
{
if(p>=La.length)
break;
Lb.elem[i]=La.elem[p];
i++;
p++;
Lb.length++;
}
}
if(j>=L.length)
{
while(p<La.length)
{
Lb.elem[i]=La.elem[p];
p++;
i++;
Lb.length++;
}
}
if(p>=La.length)
{
while(j<L.length)
{
Lb.elem[i]=L.elem[j];
p++;
j++;
Lb.length++;
}
return OK;
}
}
數據結構-順序表的基本操作
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.