请大家看看有没有什么还没有注意到的地方!
学数据结构,线性表这里,然后用C语言写着试了一下,不知道有没有什么地方没有考虑到,或者哪里实现的不对,还请大家指点!
程序代码:// 线性表.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
//typedef ElemType int ;
#define LIST_INIT_SIZE 100//线性表存储空间的初始分配量
#define LISTINCREMENT 10 //线性表存储空间的分配增量
typedef struct {
int *elem; //存储空间基地址
int length; //当前长度
int listsize; //当前分配的存储容量
}SqList;
int j=0;
int InitList_Sq(SqList &L) //初始化一个空线性表
{
L.elem=(int *)malloc(LIST_INIT_SIZE *sizeof(int));
if(!L.elem)
return 0;
L.length=0;
L.listsize=LIST_INIT_SIZE;
return 1;
}
int ListInsert_Sq(SqList &L,int i,int e) //插入操作
{
if(L.length>=L.listsize)
{
L.elem=(int *)realloc(L.elem,(LIST_INIT_SIZE+LISTINCREMENT)*sizeof(int));//进行空间再分配
if(!L.elem)
return 0;
L.listsize+=LISTINCREMENT;
}
if(i<1||i>L.length+1) //这里i的值不能小于1,也不能大于最长长度的下一个位置
return 0;
for(j=L.length-1;j>=i-1;j--)
L.elem[j+1]=L.elem[j];
L.elem[i-1]=e; //如果要插入的是第一个数,则在这里会实现
++L.length; //注意别忘了,这里的长度值要加1
return 1;
}
int ListEmpty(SqList L) //判断线性表是否为空
{
if(L.length==0)
return 1;
else
return 0;
}
int ListDelete_Sq(SqList &L,int i,int &e) //用e返回要删除的值
{
if(ListEmpty(L))
return 0;
if(i<0||i>L.length)
return 0;
e=L.elem[i-1];
for(j=i;j<L.length;j++)
L.elem[j-1]=L.elem[j]; //后面往前面移动
L.length--; //这里的length值要减一
return e;
}
int ListLength(SqList L) //求线性表的长度
{
return L.length;
}
int GetElem(SqList L,int i,int &e) //获取线性表的某个位置的元素
{
if (i<0||i>L.length)
{
return 0;
}
e=L.elem[i-1];
return e;
}
int DestoryList(SqList &L)
{
if(L.elem)
{
free(L.elem);
L.length=0;
}
return 1;
}
int ClearList(SqList &L)
{
if(L.elem)
{
L.length=0;
}
return 0;
}
int ListTraverse(SqList L)
{
if (!L.elem||ListEmpty(L)) //如果此时线性表被销毁了,或者它是空表
{
printf("It is an Empty List!");
}
else
for(int i=0;i<L.length;i++)
{
printf("%2d",L.elem[i]);
}
return 0;
}
int _tmain(int argc, _TCHAR* argv[])
{
SqList Sq;
int e;
InitList_Sq(Sq);
for(int i = 1 ;i< 5; i++)
ListInsert_Sq(Sq,i,i);
printf("%d",ListLength(Sq));
printf("\n");
printf("%d\n",GetElem(Sq,3,e));
for(int i=4;i>=1;i--)
{
printf("The element to be deleted is%2d\n",ListDelete_Sq(Sq,i,e));
printf("Now the length of the List is %3d\n",ListLength(Sq));
printf("\n");
}
ListTraverse(Sq);
ClearList(Sq);
DestoryList(Sq);
getchar();
return 0;
}
是按着书上来的,如果大家有好的代码可以发上来我学习下!或者介绍个好的网上学习数据结构的好地方!谢谢了!








