1创建一个线性表
2.对线性表进行添加,删除,查找,修改。
#include "iostream" #define OK 1 #define ERROR 0 #define MAXSIZE 100 using namespace std; typedef int ElemType; typedef int Status; typedef struct{ ElemType *elem; int length; }LinkList; //为线性表初始化 Status InitList(LinkList &L) { L.elem=new ElemType[MAXSIZE]; if(!L.elem) return ERROR; L.length=0; return OK; } //创建一个线性表 Status CreateList(LinkList &L){ int n,a; cout<<"请输入线性表的长度:"; cin>>n; cout<<"请输入元素:"; for(int i=0;i<n;i++){ cin>>L.elem[i]; } L.length=n; return OK; } Status ShowList(LinkList &L){ cout<<"输出线性表为:"; for(int i=0;i<L.length;i++){ cout<<L.elem[i]; } } //向线性表中添加元素 Status InsertList(LinkList &L,int i,ElemType e){ if((i<1)||i>L.length+1) return 0; if(L.length==MAXSIZE) return ERROR; for(int j=L.length+1;j>=i-1;j--) L.elem[j+1]=L.elem[j]; L.elem[i-1]=e; L.length++; return OK; } //线性表的删除 Status DeleteList(LinkList &L,int i){ if((i<1)||i>L.length) return ERROR; for(int j=i;j<=L.length;j++) L.elem[j-1]=L.elem[j]; L.length--; return OK; } //求线性表的长度 Status ShowLength(LinkList &L){ int length=0; for(int i=0;i<L.length;i++){ length++; } cout<<"该线性表的长度为:"<<length; } //返回元素的位置 int GetList(LinkList L,ElemType e) { for(int i=0;i<L.length;i++) { if(L.elem[i]==e) return i+1; } return 0; } //修改元素 Status ReplaceList(LinkList &L,int i,ElemType e) { for(int j=1;j<=L.length;j++) if(j==i){ L.elem[j-1]=e; } return OK; } int main(){ LinkList L; InitList(L); CreateList(L); ShowList(L); cout<<endl; cout<<"在线性表中的第二个位置插入6这个元素:"; InsertList(L,2,6); ShowList(L); cout<<endl; ShowLength(L); cout<<endl; cout<<"把线性表中第3个位置的元素删除:"<<endl; DeleteList(L,3); ShowList(L); cout<<endl; ShowLength(L); cout<<endl; int TT=GetList(L,4); cout<<"返回元素4的位置是:"<<TT<<endl; ReplaceList(L,1,7); cout<<"将第一个位置的元素换成7:"; ShowList(L); cout<<endl; ShowLength(L); }
线性表的基本操作
这篇博客介绍了如何使用C++实现线性表的基本操作,包括初始化、创建线性表、显示元素、插入元素、删除元素、查找元素位置以及修改元素。示例代码详细展示了每个操作的过程,并通过主函数演示了这些操作的实际应用。
摘要由CSDN通过智能技术生成