C语言之顺序表

一、顺序表的概念

1.顺序表的底层结构是数组

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

二、顺序表的定义

typedef  int  Datatype
typedef  struct Seqlist
{
   Datatype* arr;
   int  size;
   int  capacity;
}SL;

三、顺序表的实现

3.1 头文件

 

#include<stdio.h>
#include<assert.h>
#include<stdlib.h>
typedef int Datatype
typedef struct Seqlist//定义
{
   Datatype* arr;
   int size;
   int capacity;  
}SL;

void  SLInit(SL* ps);//初始化
void  SLDestory(SL* ps);//销毁
void  SLPrint(SL);//打印
void  SLPushBack(SL* ps,Datatype x);//尾插
void  SLPushFront(SL* ps,Datatype x);//头插
void  SLPopBack(SL* ps);//尾删
void  SLPopFront(SL* PS); //头删
void  SLInsert(SL* ps,int pos,Datatype x);//指定位置插入
void  SLEarse(SL* ps,int pos);//指定位置删除
void  SLFind(SL* ps,Datatype x);//找数据

3.2源文件

 

void SLInit(SL* ps)
{
   ps ->arr=NULL;
   ps->size=ps->capacity=0;
}   

void  SLDestory(SL* ps)
{

   if(ps->arr)
   {
      free(ps->arr);
   }
   ps->arr=NULL;
   ps->size=ps->capacity=0;
}

void  SLPrint(SL)
{
  assert(ps);
  for(int i=0;i<size;i++)
  {
     printf("%d",arr[i]);
  }
}
void  SLCheakNULL(SL* ps)
{
    if(ps->size==ps->capacity)
      {
        newcapacity=ps->capacity==0?4:ps->capacity*2;
        Datatype* tmp=(Datatype*)relloc(ps->arr,sizeof(newcapacity));
        if(tmp==NULL)
        {
           perror(realloc fail);
           exit(1);
        }
        ps->arr=tmp;
        ps->capacity=newcapacity;
      }
}
void  SLPushBack(SL*ps,Datatype x)
{
   assert(ps);
   SLCheakNULL(ps)
   ps->arr[ps->size]=x;
   ps->size++;
}

void  SLPushFront(SL*ps,Datatype x)
{
   assert(ps);
   SLCheakNULL(ps);
   for(int i=ps->size;i>0;i--)
   {
      ps->arr[i]=ps->[i-1];
   }
   ps->arr[0]=x;
   ps->size++;
}

void SLPopBack(SL*ps)
{
   assert(ps);
   assert(ps->size);
   ps->size--;
}

void  SLPopFront(SL*PS)
{
   assert(ps);
   assert(ps->size);
   for(int i=0,i<size-1;i++)
   {
      ps->arr[i]=pa->arr[i+1];
   }
   ps->size--;
}


void  SLInsert(SL*ps,int pos,Datatype x)
{
    assert(ps)
    assert(pos>=0&&pos<ps->size)
    for(int i=ps->size;i>pos;i--)
    {
       ps-arr[i]=ps->arr[i-1];
    }
    ps->arr[pos]=x;
    ps-size++;
}

void  SLEarse(SL*ps,int pos)
{
  assert(ps);
  assert(pos>=0&&pos<ps->size);
  for(int i=pos;i<ps->size-1;i++)
  {  
     ps->arr[i]=ps->arr[i+1];
  }
  pos->size--;
}

void  SLFind(SL*ps,Datatype x)
{
  assert(ps);
  for(int i=0;i<ps->size;i++)
   {
     if(ps->arr[i]==x)
      {
       return i;
      } 
   }
   return -1;
}

3.3测试文件

int main()
{
	SL s1;
	SLInit(&s1);
	SLPushFront(&s1,2);
	SLPushFront(&s1,7);
	SLPushFront(&s1,9);
	SLPushFront(&s1,8);
	SLPushBack(&s1, 7);
	SLInsert(&s1, 3, 6);
	SLEarse(&s1, 4);
	SLPrint(s1);
	
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值