设顺序表va 中的数据元素递增有序。试写一算法,将x 插入到顺序表的适当位置上,以 保持该表的有序性。

sqlist.h

#pragma once
#include<stdio.h>

typedef int Elemtype;

typedef struct Sqlist
{
    Elemtype* elem;
    int length;
    int listsize;
}Sqlist,*PSqlist;

#define INIT_SIZE 10

void  InitSqlist(PSqlist ps);
bool Insert(PSqlist ps,Elemtype x);
void Show(PSqlist ps);
bool Inserthead(PSqlist ps,int pos,int val);

sqlist.cpp

#include"sqlist.h"
#include<assert.h>
#include<stdio.h>
#include<stdlib.h>

void  InitSqlist(PSqlist ps)//初始化
{
    assert(ps!=NULL);
    if(NULL==ps)
        return;
    ps->elem=(Elemtype*)malloc(INIT_SIZE*sizeof(Elemtype));
    ps->length=0;
    ps->listsize=INIT_SIZE;
}
static void Inc(PSqlist ps)
{
    Elemtype *p=(Elemtype*)malloc(sizeof(Elemtype)*2*(ps->listsize));
    for(int i = 0;i< ps->length;i++)
    {
        p[i] = ps->elem[i];
    }
    free(ps->elem);
    ps->elem = p;

    /*ps->elem=(Elemtype*)realloc(ps->elem,(ps->listsize)*2);*/
    
    ps->listsize =ps->listsize*2;
}
static bool Full(PSqlist ps)
{
    if(ps->length==ps->listsize)
    {
    return true;
    }
    return false;
}
bool Inserthead(PSqlist ps,int pos,int val)
{
    assert(ps!=NULL);
    if(NULL==ps)
        return false;
    if(Full(ps))
    {
        Inc(ps);
    }
    for(int i=ps->length-1;i>=pos;i--)
    {
        ps->elem[i+1]=ps->elem[i];
    }
    ps->elem[pos]=val;
    ps->length++;
    return true;
}

bool Insert(PSqlist ps,Elemtype x)
 {
    assert(ps!=NULL);
    if(NULL==ps)
        return false;
    if(Full(ps))
    {
        Inc(ps);
    }
    int i;
    for(i=0;i<ps->length;i++)
    {
        if(ps->elem[i]>x)
        {
            break;
        }
    }
    for(int j=ps->length-1;j>=i;j--)
    {
        ps->elem[j+1]=ps->elem[j];
    }
    ps->elem[i]=x;
    ps->length++;
    return true;
}
void Show(PSqlist ps)
{
    assert(ps!=NULL);
    if(NULL==ps)
        return;
    for(int i=0;i<ps->length;i++)
    {
        printf("%d ",ps->elem[i]);
    }
    printf("\n");
}

main.cpp


#include"sqlist.h"
#include<stdio.h>


using namespace std;
int main()
{
    Sqlist va;
    InitSqlist(&va);
    for(int i=0;i<va.listsize;i++)
    {
        Inserthead(&va,i,i);
    }
    Show(&va);
    Insert(&va,5);
    Show(&va);


    return 0;
}

猜你喜欢

转载自blog.csdn.net/m0_43407388/article/details/107865548
今日推荐