再读数据结构

这段时间在重新阅读一本叫大话数据结构的书,书中内容通俗易懂,但是对新手不友好的就是他的代码不够齐全所以需要新手多去从网上找代码练习,鉴于我再次的开始练习数据结构,因此会把该书中的代码尽量补齐,供各位参考
第一篇是对线性表中顺序表的操作

#include <iostream>
#define Maxsize 20
using namespace std;
typedef int ElemType;
typedef struct
{
	ElemType data[Maxsize];
    int length;
}SqList;
//初始化线性表
void InitList(SqList *&L)
{
  L=(SqList *)malloc(sizeof(SqList));
  L->length=0;
}


//首先就是要建立一个顺序表  输出型参数均使用“&”类型,不论参数值是否改变
void CreateList(SqList *&L,ElemType a[], int n)
{
 int i=0,k=0;
 L=(SqList*)malloc(sizeof(SqList));
 while(i<n)
 {
 L->data[k++]=a[i];
 i++;
 }
 L->length=k;
}


//线性表中插入新元素
 bool   ListInsert(SqList *&L,int i,ElemType e)
 {
   int j;
   if(i<1||i>L->length+1)
	   return false;
   i--;//将逻辑序号转换为物理序号;
   for(j=L->length;j>i;j--)
     L->data[j]=L->data [j-1];
   L->data [i]=e;
   L->length++;
   return true;
 }


 //删除数据元素
 bool   ListInsert(SqList *&L,int i,ElemType& e)
 {
   int j;
   if(i<1||i>L->length+1)
	   return false;
   i--;//将逻辑序号转换为物理序号;
   for(j=i;j<L->length -1;j--)//为什么是j-1,比方说一共三个元素 1 2 3,现在均往前移一位,则只需要移动两次,2到1的位置,3到2的位置次数是length-1
     L->data[j]=L->data [j+1];
   L->length--;
   return true;
 }


//获取顺序表中第i个元素值
 bool GetElem(SqList *L,int i,ElemType &e)
 {
   if(L->length==0||i<1||i>L->length)
	   return false;
   e=L->data[i-1];
   return true;
 }


 //判断线性表是否为空表
 bool ListEmpty(SqList *L)
 {
  return (L->length==0);//如果为假的话说明线性表不为空
 }


 //求线性表的长度
 int LiseLength(SqList *L)
 {
 
 return (L->length);
 }


 //输出线性表
 void DispList(SqList *L)
 {
   int i=0;
  if(ListEmpty(L))
	 return;
 for(i=0;i<L->length;i++)
 {
 cout<<L->data [i];
 } 
 }


 //按照元素查找 
 int LocateElem(SqList *L,ElemType e)
 {
 int i=0;
  while(i<L->length&&L->data [i]!=e)
  {
   i++;
  }
  if (i>L->length)
	  return 0;
  else
      return i+1;
 }

 //销毁线性表
void DestoryList(SqList *&L)
{
    free(L);
}
/*
顺序表采用指针传递,有两个优点
 更清楚看到顺序表创建和销毁过程(malloc/free);
在算法的函数之间传递更加节省空间(在函数体内不必创建值形参即整个顺序表的副本)
*/

int main()
{
	SqList *L;
	int a[10]={1,2,3,4,5};
	InitList(L);
	CreateList(L,a,5);
	DispList(L);
    ListInsert(L,6,6);
	cout<<endl;
	DispList(L);
	DestoryList(L);
	DispList(L);
return 0;
}

//分析最好最坏的时间复杂度
/*
所以在长度为n的线性表中删除一个元素时所需移动元素的平均次数为:  
(n-1)/2
最好是0次就是不用移动,最坏是n-1次	*/

如有问题可留言探讨

发布了32 篇原创文章 · 获赞 4 · 访问量 2296

猜你喜欢

转载自blog.csdn.net/delete_bug/article/details/105350876