菜B要找工作了,多少学点吧!其实最开始学过数据结构,但是那个时候没有用语言实现,无从下手,应付了考试,现在害了自己!一个月之内要实现所有数据结构!
作为最简单同时也是相对重要的数据结构,线性表的表示和实现有两种方式,顺序结构和链表结构,实现了最简单的增删查,
#include<stdio.h>
#include<stdlib.h>
#define MAXSIZE 100
#define ERROR 0
#define OK 1
#define INCREACEMENT 10
typedef int Status;
typedef int ElemType;
typedef struct SqList{
ElemType *item;
int length;
}SqList;
//初始化顺序列表;
Status InitList(SqList *L)
{
(*L).item = (ElemType *)malloc(MAXSIZE*sizeof(ElemType));
if(!((*L).item))
{
printf("There is no enough space ");
exit(1);
}
(*L).length = 0;
return OK;
}
//插入元素
Status InsertList(SqList *L,int i,ElemType e)
{
int j;
if(i<1 || i>MAXSIZE)
{
printf("the wrong posation");
exit(1);
}
//还应该考虑,已经将空间存储满了,所以要重新扩容
if((*L).length >= MAXSIZE)
{
(*L).item = (ElemType *)realloc((*L).item,(MAXSIZE+INCREACEMENT)*sizeof(ElemType));
}
if(!(*L).item)
{
printf("there is no enough space");
exit(1);
}
for(j=(*L).length-1;j>=i;j--)
{
(*L).item[j+1] =(*L).item[j];
}
(*L).item[i-1] = e;
(*L).length++;
return OK;
}
//删除某个元素,将删除的元素赋值给指针e
Status DeleteList(SqList *L,int i,ElemType *e)
{
int j;
if(i<1 || i>((*L).length-1))
{
printf("the wrong position to delete");
exit(1);
}
*e = (*L).item[i-1];
for(j=i-1;j<(*L).length-1;j++)
{
(*L).item[j] = (*L).item[j+1];
}
(*L).length--;
return OK;
}
//查询某个位置的元素
ElemType LocateList(SqList *L,int i)
{
ElemType *e = (ElemType *)malloc(sizeof(ElemType));
if(i<1||i>(*L).length-1)
{
printf("the wrong position");
exit(1);
}
return *e = (*L).item[i-1];
}
int main()
{
int j;
ElemType pos;
SqList L;
ElemType *del_elem =(ElemType *)malloc(sizeof(ElemType));
InitList(&L);
for(j = 1;j<=20;j++)
{
InsertList(&L,j,j+1);
}
DeleteList(&L,6,del_elem);
pos = LocateList(&L,4);
printf("%d\n\n\n",pos);
printf("%d\n",*del_elem);
printf("%d",L.length);
while(1);
}
以前也不会C语言,其中的指针,让我想了半天,有几点应该注意一下:
1、声明了指针必须初始化,不初始化,就会造成指针悬挂,而无法使用,必须指定一个地址,有两种方式,第一种,使用malloc函数,其次,填写元素,并使用取地址符号(&)
来进行使用!
2、定义的顺序线性表结构体包括了一个数组和一个整型数据,所以,需要给数组赋值的时候,需要使用(*L).item来表示第一个元素的地址!