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

来源:互联网 发布:斗鱼诸葛网络吃蛇视频 编辑:程序博客网 时间:2024/05/18 03:48

#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;
}

0 0
原创粉丝点击