顺序表专题

前言:下文中的代码中使用int为例,实际使用中,顺序表的每一个数据可能为其他,也可能为结构体。常常使用typedef

1.顺序表的概念

顺序表的底层概念其实就是数组,顺序表在数组的基础上增加了增删查改等。它也是线性表的一种。

顺序表在物理结构连续,在逻辑结构上是一定连续的。

2.顺序表的分类

顺序表分为静态顺序表和动态顺序表,静态顺序表额、根本上就是用定长的数组来存储元素。而动态顺序表

静态顺序表使用定长数组,动态顺序表使用动态内存开辟,需要用到relloc,malloc等函数。这样的好处是可以节约系统空间。

3.顺序表定义

静态顺序表:

struct SeqList{
int arr[100];//定长数组
int length; //顺序表当前的有效数据个数
};

动态顺序表:

struct SeqList{
    int *arr;//
    int length;//有效长度
    int capacity;//空间大小
};

在实践过程中,静态顺序表使用范围很有限,不如动态顺序表灵活,而且不会浪费空间。

动态顺序表可以实现动态增容。

(1)顺序表的初始化

SLinit (SL &s){
s->arr=NULL;
s->length=s->capacity=0;//都置0
}

如果在这里实现时,要注意函数的传参。一般都要传地址,不容易出错。

(2)顺序表的销毁  

void SLDestroy(SL* sl){
if(sl->arr) free(sl->arr);
sl->arr=NULL;
sl->length = sl->capacity = 0;
}

(3)顺序表的尾插法

void SLPushBack (SL *sl,SLDataType x){
assert(sl);
    if(sl->capacity==sl->size)
{
    int newCapacity =  sl->capacity == 0?4:2*sl->capacity;
    SLDataType* tmp=(SLDataType*)realloc(sl->arr,newCapacity * sizeof(SLDataType));//申请空间  
if(tmp==NULL)
{
perror("realloc fail!");
exit(1);
} 
sl->arr =tmp;
sl->capacity=newCapacity;
}
    sl->arr[sl->length++] = x;
sl->length++;
}

(4)顺序表的头插法

void SLPushFront(SL* sl,SLDataTyPe){
    assert(sl);
      if(sl->capacity==sl->size)
{
    int newCapacity =  sl->capacity == 0?4:2*sl->capacity;
    SLDataType* tmp=(SLDataType*)realloc(sl->arr,newCapacity * sizeof(SLDataType));//申请空间  
if(tmp==NULL)
{
perror("realloc fail!");
exit(1);
} 
sl->arr =tmp;
sl->capacity=newCapacity;
}
   for(int i=sl->length;i>=1;i--){
sl->arr[i]=sl->arr[i-1];
}
sl->arr[0]=x;
sl->length++;
}

(5)顺序表的尾删法

void SLPopBack(SL* sl){
    assert(sl);
    assert(sl->length);
    //sl->arr[length-1]=-1;//
    --sl->length;
}

(6)顺序表的打印

void SLPrint(SL* sl){
assert(sl);
for(int i=0;i<=sl->length;i++){
cin>>sl->arr[i]>>endl;
}
}

(7)顺序表的头删

void SLPopFront(SL* sl){
    assert(sl);
    assert(sl->length);
    for(int i=0;i < sl->length-1;i++){
sl->arr[i]=sl->arr[i+1];
}
--sl->length;
}

(8)指定位置的插入

void SLInsert(SL* sl,int pos,int SLDataType x){
aseert(sl);
assert(pos >= 0 && pos < sl->length);
    if(sl->capacity==sl->size)
{
   int newCapacity =  sl->capacity == 0?4:2*sl->capacity;
   SLDataType* tmp=(SLDataType*)realloc(sl->arr,newCapacity * sizeof(SLDataType));//申请空间 
    if(tmp==NULL)
    {
    perror("realloc fail!");
    exit(1);
    } 
    sl->arr =tmp;
    sl->capacity=newCapacity;
}
for(int i=sl->length;i>pos;i--){
    sl->arr[i]=sl-->arr[i-1];
}
sl->arr[pos]=x;
++sl->length;
}

(9)指定位置的删除

void SLPop(SL* sl,int pos){
aseert(sl);
assert(pos >= 0 && pos < sl->length);

for(int i=length-1;i>=pos;i--){
    sl->arr[i-1]=sl-->arr[i];
}
--sl->length;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值