提起数据结构,想必大家都不陌生,说白了数据结构就是让我们学会使用一种方法对数据进行处理,使其有规律可循。废话不多说,直接上干货.
//为了编码规范
#include <iostream>
#include<stdio.h>
#include<stdlib.h>
using namespace std;
//注意语法的不同
//首先我们采用宏定义
#define MaxSize 20
//typedef
//在计算机编程语言中用来为复杂的声明定义简单的别名
typedef int ElemType;
typedef struct
{
ElemType data[MaxSize];
int length;
}SQlist;
//下面我们建立循序表
//SQlist *L与SQlist *&L的区别在于一个是指针,一个是指针的引用,即指针的地址
void CreateList(SQlist *&L, ElemType a[],int n){
int i;
L=(SQlist *)malloc(sizeof(SQlist));//分配存放线性表的空间
for(i=0;i<n;i++){
L->data[i]=a[i];
}
L->length=n;
}
//初始化循序表
void init(SQlist *&L){
L=(SQlist *)malloc(sizeof(SQlist));
L->length=0;
}
//销毁循序表
void destroy(SQlist *&L){
free(L);
}
//判断循序表是否为空表
bool isEmpty(SQlist *L){
return (L->length==0);
}
//求循序表的长度
int listLength(SQlist *L){
return L->length;
}
//输出线性表
void display(SQlist *L){
int i=0;
if(L->length==0){
printf("表中无数据\n");
exit(-1);
}
for(i=0;i<L->length;i++){
if(i%10==0)
printf("\n");
printf("%d ",L->data[i]);
}
}
//求循序表中某个数据的值
//占位符其实就是地址,在c语言中对地址进行操作才会该表数据的值
bool getElem(SQlist *L,int i,ElemType &e){
if(i<1||i>L->length){
return false;
}
e=L->data[i-1];
return true;
}
//按元素值查找位置
int getLocation(SQlist *L,ElemType e){
int i=0;
while(i<L->length&&L->data[i]!=e)
i++;
if(i>=L->length)
return 0;
//因为数组的下标是从零开始的
else return i+1;
}
//插入数据元素
//插入数据元素,数组元素就会向后移动
bool insertElem(SQlist *&L,int i,ElemType e){
int j;
if(i<1||i>L->length+1){
return false;
}
//找到在数组中的合适的位置
i--;
//数组元素向后移动
for(j=L->length;j>i;j--){
L->data[j]=L->data[j-1];
}
L->data[i]=e;
L->length++;
return true;
}
//删除数据元素
//加上占位符是将删除的数据作为结果赋给某一个值
bool deleteElem(SQlist *&L,int i,ElemType &e){
int j;
if(i<1||i>L->length){
return false;
}
//找到在数组中的要删除数据的位置
i--;
//删除数据是链表向前移动
for(j=i;j<L->length-1;j++){
L->data[j]=L->data[j+1];
}
L->length--;
return true;
}
int main()
{
cout << "welcome to the world of SQlist" << endl;
//首先我们定义了一个循序表
SQlist *L;
ElemType a[MaxSize];
int findneedle;
int location;
int elem;
int inelem;
int outelem;
int inlocation;
int outlocation;
for(int m=0;m<10;m++){
cin>>a[m];
}
//初始化循序表
init(L);
//创建线性表
CreateList(L,a,10);
//输出线性表
display(L);
cout<<endl;
//输出线性表的长度
cout<<listLength(L)<<endl;
//判断线性表是否为空表
cout<<isEmpty(L)<<endl;
cout<<"请输入您要查询位置的数据"<<endl;
cin>>findneedle;
cout<<"您要查询的数据的位置为:"<<getLocation(L,findneedle)<<endl;
cout<<"请输入您要查询数据的位置"<<endl;
cin>>location;
//因为在这一步将结构送到elem的地址
getElem(L,location,elem);
cout<<"请输入您要查询位置的数据为:"<<elem<<endl;
cout<<"请输入您要插入的数据以及位置"<<endl;
cin>>inelem>>inlocation;
insertElem(L,inlocation,inelem);
display(L);
cout<<"请输入您要删除的数据以及位置"<<endl;
cin>>outelem>>outlocation;
deleteElem(L,outlocation,outelem);
display(L);
//最后一定要把空间释放
destroy(L);
return 0;
}
在这里需要解释几点:
1,在c语言中,头文件为#include<stdio.h>,因为用到了c语言中的输出函数,当然本例中也用到了c++的函数,所以两者的头文件都要表明.
2,注意语法规范
3,注意传址与传值的区别,比如我刚入门的时候都会有疑惑,SQlist *&L与SQlist *L有什么区别呢,其实&是一个占位符,表示的是地址,在c语言里,变量的数据存放在地址里,如果你想改变一个数,则必须对其地址进行操作,同时,SQlist *L与SQlist *&L的区别在于一个是指针,一个是指针的引用,即指针的地址
下面是运行的结果,建议自己动手写一下。