这是自己第一次开始编写数据结构的代码,在此之前,进行了一个月的学习,这个月作为练习。
一开始写的很生疏,虽然在思想方面已经理解,但有很多细节做得不对,但是自己在后边都进行了测试,初学者可以参考。
在返回值方面有些问题,在后几次的练习中进行了修改。
/*只进行了年龄测试*/
/*节点个数在List_Size 里边修改*/
#include<stdio.h>
#include<stdlib.h>
#include <string.h>
#define List_Size 5
typedef struct
{
// char name[20];
// char sex;
int age;
// int ID;
}node;
typedef struct
{
node *p;
int length;
int listsize;
}list;
list l;
//创建一个空的线性表
int InitList(list &l)
{
l.p=(node *)malloc(List_Size*sizeof(node));
if(!(l.p))
{
printf("创建失败\n");
}
l.length=0;
l.listsize=List_Size;
return 0;
}
//销毁一个线性表
void DestroyList(list &l)
{
if(!(l.p))
{
printf("线性表为空\n");
}
else
{
free(l.p);
printf("线性表已销毁");
}
}
//将线性表重置为空表
int ClearList(list &l)
{
if(!(l.p))
{
printf("线性表已经是空表\n");
}
else{
free(l.p);
l.p=(node *)malloc(List_Size*sizeof(node));
l.length=0;
}
return 0;
}
//判断线性表是否为空
int ListEmpty(list &l)
{
if(l.p==NULL)
{
return 1;// 1为真
}
else{
return 0;// 0为假
}
}
//返回线性表中数据元素的个数
int ListLength(list &l)
{
return l.length;
}
//用e返回L中第i个数据元素的值
int GetElem(list &l,int i,node &e)
{
if(l.p==NULL && i<0 && i>l.length)
{
printf("线性表没有此值");
}
else{
e=l.p[i-1];
}
return 0;
}
//查找,返回e所在的位序
int LocateElem(list &l,node &e)
{
int i,n,m;
i=0;
n=sizeof(node);
while(m=memcmp(&l.p[i],&e,n))
{
i++;
if(i>l.length)
{
break;
}
}
if(m==-1||m==1)
{
printf("线性表中没有此元素\n");
return 0;
}
return i+1;
}
//得到e元素的前驱元素,用pre_e返回
int PriorElem(list &l,node &e,node &pre_e)
{
int i;
int LocateElem(list &l,node &e);
i=LocateElem(l,e);
if(!i)
{
printf("e元素不在此线性表\n");
}
else if(i==1){
printf("e元素没有前驱元素\n");
}
else{
pre_e=l.p[i-2];
}
return 0;
}
//得到e元素的后继元素,用next_e返回
int NextElem(list &l,node &e,node &next_e)
{
int i;
int LocateElem(list &l,node &e);
i=LocateElem(l,e);
if(!i)
{
printf("e元素不在此线性表\n");
}
else if(i==(l.length)){
printf("e元素没有后继元素\n");
}
else{
next_e=l.p[i];
}
return 0;
}
//在线性表 i后边中插入新的数据元素e,返回新的线性表
list ListInsert(list &l,int i,node &e)
{
int j=0;
list nl;
nl.p=(node *)malloc((List_Size+1)*sizeof(node));
nl.length=l.length+1;
while(j<i)
{
nl.p[j]=l.p[j];
j++;
}
nl.p[i]=e;
for(j=i+1;j<nl.length;j++)
{
nl.p[j]=l.p[i];
i++;
}
return nl;
}
//插入元素二
void ListInsertTwo(list &l,int i,node &e)
{
int j;
l.p=(node *)realloc(l.p,(List_Size+1)*sizeof(node));
l.length=l.length+1;
for(j=l.length-1;j>i-1;j--)
{
l.p[j]=l.p[j-1];
}
l.p[i-1]=e;
}
//返回删除的第i位置的元素
int ListDelete(list &l,int i,node &e)
{
e=l.p[i-1];
while(i<l.length)
{
l.p[i-1]=l.p[i];
i++;
}
l.length=l.length-1;
return 0;
}
//遍历线性表
int ListTraverse(list &l)
{
int i;
for(i=0;i<l.length;i++)
{
if(i%3==0)
printf("\n");
printf("\t%d",l.p[i].age);
}
return 0;
}
int main()
{
int i;
node k;
k.age=14;
InitList(l);
for(i=0;i<List_Size;i++)
{
scanf("%d",&l.p[i].age);
l.length++;
}
//加入要使用的函数
//.....
return 0;
}