顺序表操作

顺序表操作

code存放在h头文件中,调用即可

#include<iostream>
const int MAXSIZE=100;
using namespace std;

//定义顺序表结构
typedef struct{ //define structure
    int *a;
    int len;
    int listsize;
}List;

void Init_List(List &l,int n) //initialize list
{
    l.a=new int[MAXSIZE];
    for(int i=0;i<n;i++)
        cin>>(*(l.a+i));
    l.len=n;
    l.listsize=MAXSIZE;
}

void Clear_List(List &l) //clear list
{
    l.len=0;
    delete []l.a;
}

void Print_List(List l) //print list
{
    for(int i=0;i<l.len;i++)
        cout<<(*(l.a+i))<<(i==l.len-1?'\n':' ');
}

//merge list 适用于有序顺序表,调用前注意调用先排序函数(If needed)
void Merge_List(List &l1,List &l2,List &l3) //merge list
{
    l3.a=new int[MAXSIZE];
    l3.listsize=MAXSIZE;
    int *p=l1.a,*q=l2.a;
    int i=0;
    for(;p<l1.a+l1.len,q<l2.a+l2.len;){
        if(*p<*q){
            if(i>0 && l3.a[i-1]>=*p)
                p++;
            else
                l3.a[i++]=*p++;
        }
        else{
            if(i>0 && l3.a[i-1]>=*q)
                q++;
            else
                l3.a[i++]=*q++;
        }
    }
    l3.len=i;
}

void Sort_List(List &l) //Insertion Sort
{
    for(int i=1;i<l.len;i++){
        int get=l.a[i];
        int j=i-1;
        while(j>=0 && get<l.a[j]){
            l.a[j+1]=l.a[j];
            j--;
        }
        l.a[j+1]=get;
    }
}

void Del_List(List &l,int k,int &e)
{
    e=-1;
    if(k<0 || k>l.len)
        return ;
    else{
        int *p=&l.a[k-1];
        e=*p;
        int *q=l.a+l.len-1;
        for(;p<=q;p++)
            *p=*(p+1);
        l.len--;
    }
}

void Insert_List(List &l,int k,int e)
{
    if(k<1 || k>l.len+2){
        cout<<"Error: invalid index!"<<endl;
        return ;
    }
    else{
        int *q=&l.a[k-1];
        int *p=l.a+l.len;
        for(;p>q;p--)
            *p=*(p-1);
        *q=e;
        l.len++;
    }
}
  • ps: personal code notes

猜你喜欢

转载自blog.csdn.net/qq_42991793/article/details/82225435