//在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;
}