您的位置:首页 > 理论基础 > 数据结构算法

数据结构与算法---线性表

2017-04-18 20:04 225 查看
#include<stdio.h>

#include<stdlib.h>

typedef int ElementType;

#define Bool int

#define TRUE 1

#define FALSE 0

struct linearList

{

 ElementType *data;

 int MaxSize;

 int Last;

};

typedef struct linearList LinearList;

void InitList(LinearList *L,int sz)

{

 if(sz > 0)

 {

  L->MaxSize = sz;

  L->Last = 0;

  L->data = (ElementType *)malloc (sizeof(ElementType) * L->MaxSize);

 }

}

void FreeList(LinearList *L)

{

 free(L->data);

}

Bool ListEmepty(LinearList *L)

{

 return (L->Last <= 0) ? TRUE:FALSE;

}

Bool ListFull(LinearList *L)

{

 return (L->Last >= L->MaxSize) ? TRUE:FALSE;

}

int ListLength(LinearList *L)

{

 return L->Last;

}

ElementType GetElem(LinearList *L,int i)

{

 return (i<0 || i>= L->Last) ? NULL: L->data[i];

}

int LocateElem(LinearList *L ,ElementType x)

{

 int i;

 for(i=0;i<L->Last;i++)

  if(L->data[i] == x) return i;

 return -1;

}

Bool InsertElem(LinearList *L,ElementType x,int i)

{

 int j;

 if(i<0 || i> L->Last || L->Last == L->MaxSize)

  return FALSE;

 else

 {

  for(j=L->Last-1;j>=i;j--) L->data[j+1] = L->data[j];

  L->data[i] = x;

  L->Last++;

  return TRUE;

 }

}

Bool DeleteElem(LinearList *L,int i)

{

 int j;

 if(i<0 || i>= L->Last || L->Last == 0)

  return FALSE;

 else

 {

  for(j=i;j<L->Last-1;j++)

   L->data[j] = L->data[j+1];

  L->Last--;

  return TRUE;

 }

}

void printout(LinearList *L)

{

 int i;

 for(i=0;i<L->Last;i++)

 printf("%d ",L->data[i]);

 printf("\n");

}

int main()

{

 LinearList *L = (LinearList *) malloc(sizeof(LinearList));

 InitList(L,5);

 InsertElem(L,10,0);

 InsertElem(L,20,0);

 InsertElem(L,30,0);

 InsertElem(L,40,0);

 InsertElem(L,50,0);

 if(InsertElem(L,60,0))

  printout(L);

 else if(ListFull(L))

  printf("list is full,failed to insert \n");

 printout(L);

 DeleteElem(L,1);

 DeleteElem(L,1);

 printf("after twice delteions the list is\n"); 

 printout(L);

 printf("the location of data 20 is %d\n",LocateElem(L,20));

 printf("the 3rd value is %d\n",GetElem(L,2));

 FreeList(L);

 return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: