C++实现顺序表
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了C++实现顺序表,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含3146字,纯文字阅读大概需要5分钟。
内容图文
![C++实现顺序表](/upload/InfoBanner/zyjiaocheng/641/ac2f4d25ad174334b74d7af0a05926a3.jpg)
话不多说,上码!(**如有不足之处,欢迎下方评论**)
1 #include<iostream> 2 3 using namespace std; 4 5 #define MAX_SIZE 100 6 7 typedef struct{ 8 int*elems;//顺序表基址 9 int length;//元素个数 10 int size;//分配的空间 11 }SqList; 12 13 //初始化 14 bool initList(SqList&L){ 15 L.elems=new int[MAX_SIZE]; 16 if(!L.elems)return false; 17 L.length=0; 18 L.size=MAX_SIZE; 19 return true; 20 } 21 22 //添加 23 bool listAppend(SqList&L,int e){ 24 if(L.length==L.size)return false; 25 L.elems[L.length]=e; 26 L.length++; 27 return true; 28 } 29 30 //插入 31 bool listInsert(SqList&L,int i,int e){ 32 if(i<0||i>=L.length)return false; 33 if(L.length==L.size)return false; 34 for(int j=L.length-1;j>=i;j--){ 35 L.elems[j+1]=L.elems[j]; 36 } 37 L.elems[i]=e; 38 L.length++; 39 return true; 40 } 41 42 //给定元素,遍历顺序表是否存在该元素 43 void getElems(SqList&L,int &i,int e){ 44 for(int j=0;j<L.length;j++){ 45 if(L.elems[j]==e){ 46 i=j; 47 cout<<"成功找到第"<<i<<"个元素"<<e<<endl; 48 }else{ 49 cout<<"元素不在第"<<j<<"个位置\n"; 50 } 51 } 52 } 53 54 //查找指定位置的元素 55 bool byPosition(SqList&L,int i,int &e){ 56 if(i<0||i>=L.length)return false; 57 e=L.elems[i]; 58 return true; 59 } 60 61 //删除 62 void listDelete(SqList&L,int &e){ 63 for(int i=0;i<L.length;i++){ 64 if(L.elems[i]==e){ 65 for(int j=i;j<L.length;j++){ 66 L.elems[j]=L.elems[j+1]; 67 } 68 L.length--; 69 } 70 } 71 } 72 73 //销毁 74 bool listDestroy(SqList&L){ 75 if(L.elems)delete[] L.elems; 76 L.length=0; 77 L.size=0; 78 return true; 79 } 80 81 //打印 82 void listPrint(SqList&L){ 83 cout<<"元素有:"; 84 for(int i=0;i<L.length;i++){ 85 cout<<L.elems[i]<<" "; 86 } 87 cout<<endl; 88 } 89 90 //测试 91 int main(void){ 92 int i,e; 93 SqList L; 94 if(initList(L)){ 95 cout<<"初始化成功\n"; 96 }else{ 97 return -1; 98 } 99 cout<<"请输入添加元素的个数:"; 100 cin>>i; 101 for(int j=0;j<i;j++){ 102 cout<<"请输入要添加的元素:"; 103 cin>>e; 104 if(listAppend(L,e)){ 105 cout<<"成功添加元素"<<e<<endl; 106 }else{ 107 cout<<"添加元素"<<e<<"失败\n"; 108 } 109 } 110 listPrint(L); 111 cout<<"请输入插入元素的位置和元素的值"; 112 cin>>i>>e; 113 if(listInsert(L,i,e)){ 114 cout<<"成功插入元素"<<e<<endl; 115 }else{ 116 cout<<"插入元素失败\n"; 117 } 118 listPrint(L); 119 cout<<"请输入要查找的元素"; 120 cin>>e; 121 getElems(L,i,e); 122 listPrint(L); 123 cout<<"请输入要查找的位置:"; 124 cin>>i; 125 if(byPosition(L,i,e)){ 126 cout<<"成功找到元素"<<e<<endl; 127 }else{ 128 cout<<"查找失败\n"; 129 } 130 listPrint(L); 131 cout<<"请输入要删除的元素:"; 132 cin>>e; 133 listDelete(L,e); 134 listPrint(L); 135 if(listDestroy(L)){ 136 cout<<"销毁成功\n"; 137 }else{ 138 cout<<"销毁失败\n"; 139 } 140 141 system("pause"); 142 return 0; 143 }
内容总结
以上是互联网集市为您收集整理的C++实现顺序表全部内容,希望文章能够帮你解决C++实现顺序表所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。