数据结构_线性表

#include <iostream>
#include <cstdlib>
#include <algorithm>
using namespace std;

#define kd 100 //动态数组的大小 
#define zj 10  //需要增加的大小 

typedef int Status;
typedef int ElemType;
                  
typedef struct
{
ElemType *elem;
int     length; 
int   listsize;	
}sqlist;  //定义一个链表 

Status f1(sqlist &L,int n) //f1初始化链表 
{
L.elem=(ElemType *)malloc(kd*sizeof(ElemType));
if(!L.elem)  return -2;
for(int i=0;i<n;i++)
cin>>L.elem[i];
L.length=n;
L.listsize=kd;
return 1;
} 

Status f2(sqlist &L,int i,ElemType e)//在i位置插入e 
{
if(i<1||i>L.length+1) return 0;
if(L.length>=L.listsize)
{
    ElemType *newbase=(ElemType *)realloc(L.elem,(L.listsize+zj)*sizeof(ElemType));
if(!newbase) return -2;
L.elem=newbase;
L.listsize+=zj;
} 
ElemType *q=&(L.elem[i-1]);
for(ElemType *p=&(L.elem[L.length-1]);p>=q;--p)
*(p+1)=*p;
*q=e;
++L.length;
return 1;
}

Status f3(sqlist &L,int i,ElemType e) //f3删除i位置的数
{
if(i<1||i>L.length) return 0;
ElemType *p=&(L.elem[i-1]);
e=*p;
ElemType *q=&(L.elem[L.length-1]);
for(++p;p<=q;++p)
*(p-1)=*p;
--L.length;
return e;
} 

Status f4(sqlist La,sqlist Lb,sqlist &Lc) //f4实现归并 
{
ElemType *pa=La.elem;
ElemType *pb=Lb.elem;
Lc.listsize=Lc.length=La.length+Lb.length;
ElemType *pc=Lc.elem=(ElemType *)malloc(Lc.listsize*sizeof(ElemType));
if(!Lc.elem) return -2;
ElemType *pa_last=&(La.elem[La.length-1]);
ElemType *pb_last=&(Lb.elem[Lb.length-1]);
while(pa<=pa_last&&pb<=pb_last)
{
if(*pa<=*pb) *(pc++)=*(pa++);
else         *(pc++)=*(pb++);//实现链表的递增操作	 
}
while(pa<=pa_last) *pc++=*pa++;
while(pb<=pb_last) *pc++=*pb++;	
return 1;
}

int main(int argc, char *argv[])
{
    ElemType a,b,n,c,d;
    sqlist L,La,Lb,Lc;
    
cin>>a>>b>>n;

f1(L,n); //初始化 
f2(L,a,b); //线性表的插入 
for(ElemType i=0;i<L.length;i++)
cout<<L.elem[i]<<" ";
cout<<endl;

ElemType e=f3(L,a,b); //删除 
for(ElemType i=0;i<L.length;i++)
cout<<L.elem[i]<<" ";
cout<<endl;

cout<<e<<endl;

cin>>c>>d; 

f1(La,c);  //初始化 
f1(Lb,d);  //初始化 
f4(La,Lb,Lc);  //线性表的归并 
for(ElemType i=0;i<Lc.length;i++)
cout<<Lc.elem[i]<<" ";
cout<<endl;

return 0;
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值