线性表(顺序sqlist.c)

来源:互联网 发布:php入门知识 编辑:程序博客网 时间:2024/05/02 02:51
 

#include <stdio.h>
#include <stdlib.h>

#define MAX 6

typedef struct
{
 int data[MAX];
 int last;
}sqlist;


sqlist *CreateList_1()
{
 sqlist *L;

 L = (sqlist *)malloc(sizeof(sqlist));
 L->last = -1;

 return L;
}


void CreateList_2(sqlist **L)
{
 *L = (sqlist *)malloc(sizeof(sqlist));
 (*L)->last = -1;

 return;
}


void ClearList(sqlist *L)
{
 L->last = -1;

 return;
}


int LengthList(sqlist *L)
{
 return (L->last + 1);
}


int EmptyList(sqlist *L)
{
 return (-1 == L->last);
}


int GetList(sqlist *L, int pos, int *x)
{
 if ((pos < 0) || (pos > L->last)) return -1;
 *x = L->data[pos];

 return 0;
}


int LocateList(sqlist *L, int x)
{
 int i = 0;

 while (i <= L->last)
 {
  if (L->data[i] == x)  return i;
  i++;
 }

 return -1;
}


int InsertList(sqlist *L, int pos, int x)
{
 int i;

 if ((pos < 0) || (pos > L->last+1) || (L->last == MAX-1)) return -1;
 for(i=L->last+1; i>pos; i--)
 {
  L->data[i] = L->data[i-1];
 }
   L->data[i] = x;
 L->last++;

 return 0;
}


int DeleteList(sqlist *L, int pos)
{
 int i;

 if ((pos < 0) || (pos > L->last)) return -1;
 for(i=pos; i<L->last; i++)
 {
  L->data[i] = L->data[i+1];
 }
 L->last--;

 return 0;
}