算法学习第一课静态顺序表操作—练习

动态的创建一个顺序表。顺序表初始长度10,插入15个数据。并删除第五个元素并分别打印
源程序是C/C++ 综合风格。。。
/*******************02************************/
#include <iostream>
#include <stdlib.h>
using namespace std;
#define MaxSize 10
typedef int ElemType; //方便类型变化
typedef struct
{
 ElemType *elem;
 int length;
 int listsize;
} Sqlist;
/*初始化一个顺序表*/
//参数L:Sqlist 类型的指针
void InitSqlist(Sqlist *L)
{
 L->elem = (int *)malloc(MaxSize*sizeof(ElemType));
 if(!L->elem) exit(0);
 L->length = 0;
 L->listsize = MaxSize;
}
/*向顺序表中插入元素*/
//参数L:Sqlist 类型指针
//参数i:插入元素位置
//参数item:插入元素
void InsertElem(Sqlist *L,int i,ElemType i_ele)//向顺序表L中第i个位置插入i_ele元素
{
 ElemType *base,*insertPtr,*p;
 if(i<1 || i>L->length+1) exit(0);
 if(L->length>=L->listsize)
 {
  base = (ElemType*)realloc(L->elem,(L->listsize+10)*sizeof(ElemType));
  L->elem = base;
  L->listsize = L->listsize + 100;
 }
 insertPtr = &(L->elem[i-1]);
 for(p=&(L->elem[L->length-1]);p>=insertPtr;p--)
  *(p+1) = *p;
 *insertPtr = i_ele;
 L->length ++;
}
//从顺序表删除元素
//参数L:Sqlist 类型指针
//参数i:删除元素的位置
void DelElem(Sqlist *L,int i)//删除位置i处的元素
{
 ElemType *del_ele,*p;
 if(i<1 || i>L->length) exit(0);
 del_ele = &(L->elem[i-1]);
 p = L->elem + L->length - 1;
 for(++del_ele;del_ele<=p;++del_ele)
  *(del_ele-1) = *del_ele;
 L->length --;
}
//test main
int main()
{
 Sqlist l;
 InitSqlist(&l);
 for(int i=0;i<15;i++)
  InsertElem(&l,i+1,i+1);
 cout<<"The content of the list is"<<endl;
 for(i=0;i<l.length;i++)
  cout<<l.elem[i]<<" ";
 cout<<endl;
 DelElem(&l,5);
 cout<<"Delete the fifth element "<<endl;
 for(i=0;i<l.length;i++)
  cout<<l.elem[i]<<" ";
 cout<<endl;
 return 0;
}

发布了21 篇原创文章 · 获赞 3 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/fafactx/article/details/14004303