数据结构之线性表基本操作(C++)
#include <iostream>
#include <cstdlib>
#define LIST_INT_SIZE 100 //线性表存储空间的初始分配量
#define LISTINCREMENT 10 //线性表存储空间的分配增量
using namespace std;
typedef struct {
int *elem; //存储空间的基地址
int length; //当前线性表的长度
int listsize; //当前分配的存储容量
}Sqlist;
//创建线性表
void InitList_Sq(Sqlist &L){
//开辟一块存储空间,并把这块存储空间的及地址赋值给elem
L.elem = (int *)malloc(LIST_INT_SIZE * sizeof(int));
if(!L.elem){
cout << "空间分配失败";
}
L.length = 0; //当前长度
L.listsize = LIST_INT_SIZE; //当前分配量
}
//像线性表中添加元素
Sqlist ListInsert_Sq(Sqlist &L,int i,int e){
if(i < 1 || i > L.length + 1)
cout << "您插入的位置有误";
if(L.length >= L.listsize){
int *newbase = (int *)realloc(L.elem,(L.listsize + LISTINCREMENT) * sizeof(int));
L.elem = newbase;
L.listsize += LISTINCREMENT;
}
int *p,*q;
q = &(L.elem[i - 1]);
for(p = &(L.elem[L.length - 1]);p >= q;--p){
*(p + 1) = *p;
}
*q = e;
++L.length;
return L;
}
//删除元素
Sqlist ListDelete_Sq(Sqlist &L,int i){
if(i < 1 || i > L.length){
cout << "位置不合法!" << endl;
}
int *p,*q;
p = &L.elem[i - 1];
q = &(L.elem[L.length - 1]);
for(++p;p <= q;++p){
*(p - 1) = *p;
}
--L.length;
return L;
}
//查找元素位置(只能找最靠前的元素)
void locateElem_Sq(Sqlist L,int x){
int pos = -1;
for(int i = 0;i < L.length;i++){
if(L.elem[i] == x){
pos = i + 1;
break;
}
}
if(pos == -1){
cout << "不存在这个元素" << endl;
}
else
cout << "元素的位置为第" << pos << "位" << endl;
}
//打印线性表
void print(Sqlist L){
for(int i = 0;i < L.length;i++){
cout << L.elem[i] << " ";
}
cout << endl;
}
int main(){
int select,a[100],n,insert_loc,e,j,q;
Sqlist L;
InitList_Sq(L);
cout << "********主要功能********" << endl;
cout << "------1.像线性表中添加元素------" << endl;
cout << "------2.打印线性表------" << endl;
cout << "------3.像线性表中插入元素------" << endl;
cout << "------4.删除元素------" << endl;
cout << "------5.查找元素位置------" << endl;
while(true){
cout << "请输入您的选择:" << endl;
cin >> select;
switch(select){
case 1:
cout << "请输入要向线性表中添加的元素个数:" << endl;
cin >> n;
cout << "请输入添加的元素:" << endl;
for(int i = 0;i < n;i++){
cin >> a[i];
ListInsert_Sq(L,i + 1,a[i]);
}
break;
case 2:
print(L);
break;
case 3:
cout << "请输入插入元素的位置" << endl;
cin >> insert_loc;
cout << "请输入插入的元素:" << endl;
cin >> e;
ListInsert_Sq(L,insert_loc,e);
break;
case 4:
cout << "请输入要删除元素的位置:" << endl;
cin >> j;
ListDelete_Sq(L,j);
break;
case 5:
cout << "请输入要查找的元素:" << endl;
cin >> q;
locateElem_Sq(L,q);
break;
}
}
}
说几个我开始学习数据结构时候的疑惑,其实我最开始理解这些东西的时候,能够理解这些操作,但是不理解取地址符号指针这些,还有->和.的区别,下面我按照我个人目前阶段的理解,解释一下
-
函数参数里面的L是否加取地址符号,取决于你是否对线性表L进行操作,就比如增加元素和删除元素,是对线性表L进行操作所以加取地址符号;而查找元素和打印元素这些,并未对线性表进行操作,所以不需要
-
还有就是c语言代码和c++代码的区别,C语言中是不支持引用写法的也就是Sqlist &L这种,对应的要把&替换成指针
-
至于->和. :
-
-> : ->是指针指向其成员的运算符。 . 是结构体的成员运算符。最大的区别是->前面放的是指针,而.前面跟的是结构体变量。
-