C++ 静态线性表的顺序存储结构(数组实现)
生活随笔
收集整理的這篇文章主要介紹了
C++ 静态线性表的顺序存储结构(数组实现)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
描述
主題:C++ 靜態線性表的完整實現
功能:分別實現靜態鏈表的插入、刪除、查找操作
提示:如果需要進入下一步操作,輸入錯誤的范圍即可
代碼
//主題:靜態鏈表 //功能:分別實現靜態鏈表的插入、刪除、查找操作 //提示:如果需要進入下一步操作,輸入錯誤的范圍即可#include<stdio.h> #include<iostream> #include<string> #define MAXSIZE 50//靜態線性表的最大長度//靜態 typedef struct StaticSequenceList {int data[MAXSIZE];//元素int length = 0;//當前長度 }SqList;//插入:在順序表L的第i個位置插入新元素e bool ListInsert(SqList &L, int i, int e) {if (i<1 || i>L.length + 1){std::cout << "位置超出范圍\n";return false;}if (L.length >= MAXSIZE){std::cout << "鏈表已滿\n";return false;}for (int j = L.length; j >= i; j--){L.data[j] = L.data[j - 1];}L.data[i - 1] = e;L.length++;return true; }//刪除:刪除順序表L中第i個位置的元素,被刪除的元素由e返回 bool ListDelete(SqList &L, int i, int e) {if (i<1 || i>L.length){std::cout << "位置超出范圍\n";return false;}e = L.data[i - 1];for (int j = i; j < L.length; j++){L.data[j - 1] = L.data[j];//前移}L.length--;return true; }//查找:查找值為e的元素,如果查找成功,返回元素位序,否則返回0 int LocateElem(SqList L, int e) {int i;for (i = 0; i < L.length; i++){if (L.data[i] == e){return i + 1;}}return 0; }int main() {//靜態SqList StaticList;int i;//位置int e;//元素bool checker = true;std::cout << "成功創建靜態線性表\n\n";//插入for (; checker != false;){std::cout << "\n(總長度:" << MAXSIZE << "當前長度:" << StaticList.length << ")\n插入操作 請輸入:位置 元素 ";std::cin >> i >> e;//ListInsert(StaticList, i, e);//輸入錯誤不退出checker = ListInsert(StaticList, i, e);//輸入錯誤則退出//打印std::cout << std::endl;for (int print = 0; print < StaticList.length; print++){std::cout << StaticList.data[print] << " ";}}//刪除std::cout << "進入刪除操作\n";for (checker = true; checker != false;){std::cout << "\n(總長度:" << MAXSIZE << "當前長度:" << StaticList.length << ")\n刪除操作 請輸入:位置";std::cin >> i;//ListInsert(StaticList, i, e);//輸入錯誤不退出checker = ListDelete(StaticList, i, e);//輸入錯誤則退出//打印std::cout << std::endl;for (int print = 0; print < StaticList.length; print++){std::cout << StaticList.data[print] << " ";}}//查找std::cout << "進入查找操作\n";int ret;for (ret = -1; ret != 0;){std::cout << "\n(總長度:" << MAXSIZE << "當前長度:" << StaticList.length << ")\n查找操作 請輸入:元素";std::cin >> e;//ListInsert(StaticList, i, e);//輸入錯誤不退出ret = LocateElem(StaticList, e);//輸入錯誤則退出//打印std::cout << "你要查找的元素在第" << ret << "個\n";}system("pause"); }總結
以上是生活随笔為你收集整理的C++ 静态线性表的顺序存储结构(数组实现)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C++ 动态线性表的顺序存储结构(数组实
- 下一篇: C++ 静态链表(用数组模拟动态链表)