数据结构-线性表


1
#include<stdio.h> 2 #define MaxSize 10 //宏定义后不加‘;’ 3 4 typedef struct { 5 //结构体中可以不初始化,这里初始化是为了方便后面使用测试 6 int data[MaxSize] = {1,3,5,2}; 7 int length = 4; 8 }SqList; 9 10 //插入 11 //L为顺序表 i为插入位置 e为插入元素 12 bool listInsert(SqList &L,int i,int e){ 13 if(i<1||i>L.length+1){ 14 //注意范围:1代表第一个元素 L.length+1表示现有末尾元素+1的位置 15 return false; 16 } 17 if(L.length>=MaxSize){ 18 //注意范围:等于最大也不行,在数组中没有最大的位置(数组下标从零开始) 19 return false; 20 } 21 for(int j=L.length;j>=i;j--){ 22 //元素后移 先从长度最后的位置移动 23 L.data[j] = L.data[j-1]; 24 } 25 L.data[i-1] = e; 26 L.length++;//最后注意长度+1 27 return true; 28 } 29 30 //删除 31 //L为顺序表 i为插入位置 e为插入元素 32 bool deleteList(SqList &L,int i,int &e){ 33 if(i<1||i>L.length){ 34 return false; 35 } 36 e = L.data[i-1]; 37 for(int j = i;j<=L.length;j++){ 38 L.data[j-1] = L.data[j]; 39 } 40 L.length--; 41 return true; 42 } 43 44 45 int main(){ 46 SqList L; 47 //测试插入方法 48 // listInsert(L,14,43); 49 // for(int i = 0;i<L.length;i++){ 50 // printf("%d ",L.data[i]); 51 // } 52 //测试删除方法 53 // int i,e; 54 // deleteList(L,2,e); 55 // printf("%d ",e); 56 // for(int i = 0;i<L.length;i++){ 57 // printf("%d ",L.data[i]); 58 // } 59 60 61 }

  以上内容主要针对数据结构的线性表中顺序存储的实现(插入和删除功能)

posted on 2019-06-26 09:34  楠楠要上天  阅读(119)  评论(0编辑  收藏  举报