线性表——长度为n的线性表A采用顺序存储结构,删除所有值为item的数据元素 时间复杂度为O(n)、空间复杂度为O(1)
//“MergeList.h #include <iostream> #define MAXSIZE 100 #define ElemType int using namespace std; typedef struct { ElemType *elem; int length; } SqList; string InitList(SqList &L){ L.elem = new ElemType[MAXSIZE]; if(!L.elem) return "OVERFLOW"; L.length = 0; return "OK"; } ElemType GetElem(SqList L,int i ){ if(i<1 || i > L.length) return 0; return L.elem[i-1]; } int LocalElem(SqList L,ElemType e){ for(int i = 0;i<L.length;i++){ if(L.elem[i] == e) return i+1; } return 0; } string ListInsert(SqList &L,int i,ElemType e){ //if(i<1||i>L.length) return "ERROR"; 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"; } string ListDelete(SqList &L,int i ){ if(i<1||i>L.length) return "ERROR"; for(int j = i-1;j<L.length;j++) L.elem[j] = L.elem[j+1]; --L.length; return "OK"; } void ShowList(SqList L){ cout << "show the list"<<endl; for(int i=0; i<L.length;i++){ cout << L.elem[i] <<" "; } } string FillListWithNum(SqList &L,int i){ for(int j=1;j<=i;j++){ ElemType p; cin>>p; ListInsert(L,j,p); } return "OK"; } // ShowList(L); // cout << "Delete"<<endl; // cout << ListDelete(L,2); // ShowList(L); // cout<<"!"; // return 0; // }
#include<iostream> #include"MergeList.h" using namespace std; /* 长度为n的线性表A采用顺序存储结构,删除所有值为item的数据元素 时间复杂度为O(n)、空间复杂度为O(1) */ int main(){ SqList LA; InitList(LA); cout <<"How long"<<endl; int num ; cin >> num; FillListWithNum(LA,num); ElemType item = 5 ; int step = 0; //记录保留元素需要前移的步数 for(int i=0;i<num;i++){ if(LA.elem[i] == item){ //循环里操作步骤与n无关,时间复杂度为O(1) step++; LA.length--; }else { LA.elem[i-step] = LA.elem[i]; } } ShowList(LA); system("pause"); return 0; }
如果遍历到与item值相同的,调用Delete函数,将后续的元素前移,则每一次遍历的时间复杂度为O(n)