#include<stdio.h>
#include<stdlib.h>
#include<iostream>
using namespace std;
#define LISTSIZE 100
#define LISTINCREMENT 10
typedef int ElementType;
typedef struct Llist *SqList;
struct Llist
{
ElementType* elem;
int length;
int listsize;
};
SqList InitList(SqList L)
{
L=(SqList)malloc(sizeof(SqList));
L->elem=(ElementType*)malloc(LISTSIZE*sizeof(ElementType));
if(L->elem==NULL)
{
printf("out of space\n");
}
L->length=0;
L->listsize=LISTSIZE;
return L;
}
void DestroyList(SqList L)
{
L->length=0;
L->listsize=LISTSIZE;
free(L->elem);
L->elem=NULL;
}
void ClearList(SqList L)
{
L->length=0;
}
bool IsEmpty(SqList L)
{
if(L->length==0)return true;
else return false;
}
int Getlength(SqList L)
{
return L->length;
}
ElementType GetElement(SqList L,int i)
{
if(i<=0||i>L->length)
{
printf("error!\n");
return 0;
}
return L->elem[i];
}
SqList InsertList(SqList L,int i,ElementType X)
{
if(i<=0||i>L->length+1)
{
printf("error!\n");
return L;
}
if(L->length>=L->listsize)
{
ElementType *newbase;
newbase=(ElementType*)realloc(L->elem,(L->listsize+LISTINCREMENT)*sizeof(ElementType));
if(!newbase)
{
printf("out of space!\n");
return L;
}
L->elem=newbase;
L->listsize+=LISTINCREMENT;
}
int p;
for(p=L->length-1;p>=i-1;p--)
{
L->elem[p+1]=L->elem[p];
}
L->elem[p+1]=X;
L->length++;
return L;
}
SqList DeleteList(SqList L,int i)
{
if(i<1||i>L->length)
{
printf("error!\n");
return L;
}
int p=i;
for(p;p<=L->length-1;p++)
{
L->elem[p-1]=L->elem[p];
}
L->length--;
return L;
}
void Print(SqList L)
{
for(int i=0;i<L->length;i++)
{
cout<<L->elem[i]<<" ";
}
}
int main()
{
SqList L;
L=InitList(L);
L=InsertList(L,1,1);
L=InsertList(L,1,2);
L=InsertList(L,1,3);
L=InsertList(L,1,4);
Print(L);
L=DeleteList(L,2);
Print(L);
system("pause");
return 0;
}
数据结构——线性表
最新推荐文章于 2024-07-09 19:36:25 发布