c++ 线性表之顺序储存结构 左插入 右插入 删除元素

//在c++ builder 平台调试通过

#include <iostream>
#include <string>
using namespace std;
#define Size 5
typedef struct Table
{
    int *head;
    int length;
    int size;
}table;

table initTable()
{
    table t;
    t.head=(int*)malloc (Size*sizeof(int));
    if (!t.head)
    {
      printf("初始化失败");
      exit(0);
    }
    t.length=0;
    t.size=Size;
    return t;
}

void displayTable(table t)
{
    for (int i=0; i < t.length; i++)
    {
       printf("%d ",t.head[i]);
    }
    printf("\n");
}
table LeftInsertTable(table &t,int pos,int elem)//左插入
{ if (pos>t.length||pos<0)
    {
        printf("插入位置有问题\n");
        return t;
    }

if(t.length==t.size)
  {
      t.head=(int *)realloc(t.head,(t.size+1)*sizeof(int));
      if(!t.head)
      {
          printf("存储分配失败\n");
          return t;
      }
      t.size+=1;

  }

  for (int i = ( t.length-1); i >= pos; i--)
  {
    t.head[i+1]=t.head[i];
  }
  t.head[pos]=elem;
  t.length++;

}
table RightInsertTable(table &t,int pos,int elem)//右插入
{

    return LeftInsertTable(t,pos+1,elem);
}

table DeleteAtTable(table &t,int pos)//删除某个位置的元素
{
   for (int i = pos ; i<( t.length-1); i++)
  {
    t.head[i]=t.head[i+1];
  }
  t.length--;

 return t;
}


int _tmain(int argc, _TCHAR* argv[])
{
    table t=initTable();
    for (int i=0; i <Size; i++)
    {
        t.head[i]=i+1;
        t.length++;
    }
    printf("顺序表中存储的元素是:\n");
    displayTable(t);
    LeftInsertTable(t,0,10);
    displayTable(t);
    RightInsertTable(t,0,20);
    displayTable(t);

    DeleteAtTable(t,6);
    displayTable(t);
    if(t.head)
    {
        free(t.head);
        t.head=0;
    }
    system("pause");
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值