线性表的线性存储及基本操作

来源:互联网 发布:高校法学教学软件 编辑:程序博客网 时间:2024/05/17 02:46

这是线性表的线性存储的实现,是的C实现的,少量用了C++的cout,纯属偷懒。

#include<iostream>#include <stdio.h>#include <stdlib.h>using namespace std;#define MAXSIZE 20    #define LISTINCREMSIZE 10  //宏定义 当最大容量不够时,每次增加的容量。typedef int Elemtype;typedef struct {Elemtype *elem;  //线性表的数据存储,利用数组来实现,这里定义的是指向数组的首元素的  指针。    int length;  //线性表当前的长度    int listsize;  //线性表的最大容量}Sqlist;//线性表的初始化void  InitSqlist(Sqlist &L){L.elem = (Elemtype *)malloc(sizeof(Elemtype[MAXSIZE]));if(!L.elem){cout<<"初始化失败"<<endl;exit(-1);}L.length = 0;L.listsize = MAXSIZE;}//创建线性表void CreatSqlist(Sqlist &L,int n){cout<<"请输入线性表中的数据:"<<endl;for(int i=0;i<n;i++){scanf("%d",&L.elem[i]);L.length++;}}//销毁线性表void ClearSqlist(Sqlist &L){cout<<"线性表被销毁!"<<endl;free(L.elem);}//在 L 的 i 位置插入数据 x      (线性表我们一般默认第一个元素的位置是1,所以在判断位置时,稍加注意)void InsertSqlist(Sqlist &L,int i,Elemtype x){// 首先要判断插入的位置是否合法if(i < 1 || i > L.length+1){cout<<"插入位置不合法!"<<endl;return;}//判断当前的容量是否已经是最大容量,如果是,则没有空间容纳新插入的元素,需重新增加空间,这里用的是  realloc 函数。它是在原来空间的基础上增加空间。if(L.length>=MAXSIZE){Elemtype *p = (Elemtype *) realloc(L.elem,(MAXSIZE + LISTINCREMSIZE)*sizeof(Elemtype));if(!p){cout<<"初始化失败"<<endl;exit(-1);}//数组指向新开辟的空间L.elem = p;L.listsize = L.length + LISTINCREMSIZE;}// 将插入位置的元素向后挪动。int j;for(j = L.length;j >= i;j--){L.elem[j] = L.elem[j-1];}//插入x, 长度增加1L.elem[j] = x;L.length++;}//删除 pos 位置上的数据void deleteSqlist(Sqlist &L,int pos){if(pos < 1 || pos > L.length){cout<<"删除位置不合法!"<<endl;return;}if(pos == L.length);for(int i=pos-1;i<L.length-1;i++){L.elem[i] = L.elem[i+1];}L.length--;}//显示数据void DispSqlist(Sqlist L){for(int i=0;i<L.length;i++){cout<<L.elem[i]<<" ";}cout<<endl;}//对线性表内数据进行排序(冒泡)void SortSqlist(Sqlist &L){int i,j;for(i=0;i<L.length;i++){for(j=1;j<L.length-i;j++){if(L.elem[j-1] > L.elem[j]){int temp = L.elem[j];L.elem[j] = L.elem[j-1];L.elem[j-1] = temp;}}}}int main(){int n;cout<<"输入线性表元素个数n:";scanf("%d",&n);Sqlist L;InitSqlist(L);CreatSqlist(L,n);DispSqlist(L);InsertSqlist(L,3,12);cout<<"插入元素后:"<<endl;DispSqlist(L);SortSqlist(L);cout<<"用冒泡排序排序后:"<<endl;//deleteSqlist(L,7);DispSqlist(L);ClearSqlist(L);DispSqlist(L);return 0;}


在win7系统 VS2010运行程序结果如下:


0 0
原创粉丝点击