顺序线性表代码

各个分步骤的具体实现算法书本上都有,而且不看书自己也可以解决。

下面就是代码的具体实现细节。对于初学者希望有所帮助。

具体注释都会写在代码中,不懂的我们可以交流学习。

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAXSIZE 20
typedef int ElemType;
typedef struct
{
ElemType data[MAXSIZE];
int length;
/*线性表当前长度*/
}SqList;

#define OK 1
#define ERROR 0
#define TURE 1
#define FALSE 0
typedef int Status;/*Status是函数类型,其返回值可以为结果状态代码,就是上面定义的ERROR OK等*/
//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
//初始化链表
Status initList(SqList &L)
{
if (!L.data)//为什么这句就把L给初始化了??????(就仅仅这一句(if(L.data))就给初始化了)//和这句没关系,我懂了
{
printf("初始化失败
");
exit(0);
}
else{
printf("初始化成功
");
}
L.length=0;
//return L//return 不是必要的,取决于调用方式;
}
//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
//return the elem of sqlist
Status GetElem(SqList L,int i,ElemType *e)//使用指针*e就不需要返回值了。
{

if(L.length==0||i>L.length)
{
printf("Read the position error
");
return ERROR;
}
*e=L.data[i-1];
return OK;
}

//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
//insert elem to sqlist
Status ListInsert(SqList *L,int i,ElemType e)//插入数据不需要用*e;此处i为第几个,不是从零开始
{
int k;
if(i<1||i>L->length+1)//此处不能用L.length 因为不是*L,而是&L
{    
printf("插入位置有误
");
return ERROR;
}
if(L->length==MAXSIZE)
{
printf("数组已经满
");
return ERROR;
}
if(i=L->length+1)//插入尾部
{
L->data[L->length]=e;

}
if(i<=L->length)//不插入尾部
{
for(k=L->length-1;k>=i-1;k--)
{
L->data[k+1]=L->data[k];
}
L->data[i-1]=e;
}

L->length++;
}

///delect the element of List
//delect the ith elemnet of List,and return the value by e
Status ListDelete(SqList *L,int i,ElemType *e)//if in the form of SqList *L is SqList L,It just is parameter,then it will not changed the L
{    

int k;
if(i<1||i>L->length)
{
printf("read the position error
");
return ERROR;    
}
*e=L->data[i-1];
for(k=i-1;k<=L->length-1;k++)
{
L->data[k]=L->data[k+1];
}
L->length--;
return OK;
}

 

int main()
{    
int j;
int *a;
int b;
int s;
int i,w;//w代表位置
Status tureOrFalse;
//////////////////initialize the list
SqList L;//已经初始化
initList(L);  /////////////////插入元素 ElemType ee; for(i=0;i<3;i++)//插入3个数字试试 { printf("请输入要插入的位置和数字(a和b)"); scanf("%d%d",&w,&ee); ListInsert(&L,w,ee);//&&&&不能用*啊,只能用&,&代表地址,   } printf("____________________
"); /////////////////取出元素 ElemType *e; e=&b; for(i=0;i<L.length;i++)//use L.length to read all data { printf("请输入要读取的位置"); scanf("%d",&w); tureOrFalse=GetElem(L,w,e);//L是个结构体类型,w是个整形,e是指针, if(tureOrFalse==OK) { printf("取出的元素为%d
",*e); } } printf("__________________________
"); //////////////////delete the Element  j=L.length; for(i=0;i<j+2;i++)//use L.length to delect all data; { printf("当前数组长度%d
",L.length); printf("请输入要删除的数据的位置 "); scanf("%d",&w); tureOrFalse=ListDelete(&L,w,e);//&L  if(tureOrFalse==OK) { printf("Delete data is:%d
",*e); } printf("____________________
"); } printf(">>>>>>>>>>>>>>>>WELL DONE>>>>>>>>>>>>>>
"); while(1); }
》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》
原文地址:https://www.cnblogs.com/ssws/p/11671585.html