构造顺序表--合并两个按元素从小到大排列的顺序表

/*******************************顺序表***************************/
#include<stdio.h>
#include<stdlib.h>//malloc,realloc,exit
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define INFEASIBLE -1
#define OVERFLOW -2
#define LIST_INIT_SIZE 100
#define LISTINCREMENT 10
typedef int Status;
typedef int ElemType;
typedef struct{         //结构
 ElemType *elem;     //L.elem[i]表示第i+1个位置的元素的值,等价于*(L.elem+i)
 int length;
 int listsize;
}SqList;
Status InitList_Sq(SqList &L){              //初始化
    L.elem=(ElemType *)malloc(LIST_INIT_SIZE*sizeof(ElemType));//malloc
 L.length=0;
 L.listsize=LIST_INIT_SIZE;
 return OK;
}
Status ListInsert_Sq(SqList &L,int i,ElemType e){               //插入元素
 ElemType *newbase,*q,*p;
 if(i<1||i>L.length+1) return ERROR;
 if(L.length>=L.listsize)
 {
        newbase=(ElemType *)realloc(L.elem,(L.listsize+LISTINCREMENT)*sizeof(ElemType));//realloc
     if(!newbase) exit(OVERFLOW);
   L.elem=newbase;
  L.listsize+=LISTINCREMENT;
 }
    q=&(L.elem[i-1]);//
 for(p=&(L.elem[L.length-1]);p>=q;--p) *(p+1)=*p;
 *q=e;
 ++L.length;
 return OK;
}
Status ListDelete_Sq(SqList &L,int i,ElemType &e)//删除元素   //实参前加&,主函数中值被修改,相当于实参是指针
{
 ElemType *p,*q;
 q=L.elem +L.length-1;
 e=L.elem[i-1];
 for(p=L.elem+i;p<=q;p++)
 {
        *(p-1)=*p;
 }
 L.length--;
 return OK;
}
void MergeList(SqList La,SqList Lb,SqList &Lc)//把两个按元素从小到大排列的顺序表合并
{
    ElemType *pa,*pb,*pc,*pa_last,*pb_last;
 pa=La.elem;
 pb=Lb.elem;
 Lc.length=0;
 Lc.listsize=La.length+Lb.length;
    pc=Lc.elem=(ElemType*)malloc(Lc.listsize*sizeof(ElemType));
 if(!Lc.elem) exit(OVERFLOW);
    pa_last=La.elem+La.length-1;
    pb_last=Lb.elem+Lb.length-1;
 while(pa<=pa_last&&pb<=pb_last)
 {
        if(*pa<*pb) *pc++=*pa++;//*pc=*pa; pa++; pc++;
  else if(*pa=*pb) {*pc++=*pa++; pb++; }
  else *pc++=*pb++;
  Lc.length++;
 }
 while(pa<=pa_last) {*pc++=*pa++; Lc.length++;}
 while(pb<=pb_last) {*pc++=*pb++; Lc.length++;}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值