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

1.数据结构之线性表的顺序存储

2011-09-04 21:24 726 查看
#include <stdio.h>
#include <stdlib.h>

#define Description LinkListSquence
#define SIZE 20

typedef int type;
typedef int bool;

typedef struct{
type data[SIZE];
int length;
}List;

List * InitList(List *list);
bool ListEmpty(List *list);
List * ClearList(List *list);
type GetElem(List *list,int index);
int LocateElem(List *list,type element);
int ListLength(List *list);

bool ListInsert(List * list,int index,type element);
bool ListAppend(List * list,type element);
type ListDelete(List *list,int index);

void ShiftToRight(List * list,int index);
void ShiftToLeft(List * list,int index);

int main(int argc, char ** argv)
{
List list;
type ele ;
InitList(&list);

if(ListEmpty(&list))
{
printf("empty\n");
}
ele = 0;
ListAppend(&list,ele);
printf("length:%d\n",list.length);

ListInsert(&list,list.length-1,ele+1);
printf("length:%d\n",list.length);

return 0;
}

List * InitList(List *list)
{
list->length = 0;
return list;
}

bool ListEmpty(List *list)
{
if(list->length == 0)
{
return 1;
}
return 0;
}

bool ListFull(List * list)
{
return list->length == SIZE;
}

/*Clear the list ,so that can use the element*/
List * ClearList(List *list)
{
list->length = 0;
return list;
}

/*get a element by index*/
type GetElem(List *list,int index)
{
return list->data[index];
}

/*get the index of the element in the list*/
int LocateElem(List *list,type element)
{
int i = list->length - 1;
for(; i >= 0; i--)
{
if(list->data[i] == element)
{
return i;
}
}
return -1;
}

int ListLength(List *list)
{
return list->length;
}

/*index starts with 0 to SIZE-1 */
bool ListInsert(List * list,int index,type element)
{
if(list->length < SIZE && index < SIZE)
{
int i = list->length - 1;
for(;i > index;i--)
{
ShiftToRight(list,i);
}
list->data[index] = element;
list->length++;
return 1;
}

return 0;
}

bool ListAppend(List * list,type element)
{
if(list->length < SIZE)
{
list->data[list->length] = element;
list->length++;
return 1;
}

return 0;
}

/*index starts with 0 to SIZE-1  */
bool ListDelete(List *list,int index)
{
if(list->length < SIZE && index < SIZE)
{
int i = index;
for(;i <= list->length - 1;i++)
{
ShiftToLeft(list,i);
}
list->length--;

return 1;
}

return 0;
}

void ShiftToRight(List * list,int index)
{
list->data[index+1] = list->data[index];
return ;
}

void ShiftToLeft(List * list,int index)
{
list->data[index-1] = list->data[index];
return ;
}


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