顺序表3中删除元素的方式(你造吗)
#include<iostream> #include<cstring> #include<string> #include<queue> #include<map> #include<cstdio> using namespace std; template <typename T> class Sqlist{ public: T data[100]; int n; void initData(); void deleteXone(T x); void deleteXtwo(T x); void deleteXthree(T x); void outData(); private: }; template <typename T> void Sqlist<T>::outData(){ for(int i=0; i<n; ++i) cout<<data[i]<<" "; cout<<endl; } template <typename T> void Sqlist<T>::initData(){ cin>>n; for(int i=0; i<n; ++i) cin>>data[i]; } template <typename T> void Sqlist<T>::deleteXone(T x){ int k = 0; for(int i=0; i<n; ++i) if(data[i] != x)//如果当前元素是 x,那么忽略该元素 data[k++] = data[i]; n = k; outData(); } template <typename T> void Sqlist<T>::deleteXtwo(T x){ int k = 0;//记录空位的数目 for(int i=0; i<n; ++i){ if(data[i]==x) ++k; else data[i-k] = data[i];//向前移动k个位置 } n = n-k; outData(); } template <typename T> void Sqlist<T>::deleteXthree(T x){ int i=0, j=n-1, k=0; while(i < j) {//不断的将data右边非x的元素 移向 data左边是x的元素的位置 while(data[i]!=x && i<j) ++i; while(data[j]==x && i<j) --j; if(i>=j) break; data[i] = data[j]; ++k; } n = n-k; outData(); } int main() { Sqlist<int> sq; sq.initData(); sq.deleteXone(2); sq.deleteXtwo(0); sq.deleteXthree(4); return 0; } /* 10 1 2 0 3 4 6 8 5 9 7 */
本文来自博客园,作者:hjzqyx,转载请注明原文链接:https://www.cnblogs.com/hujunzheng/p/4665697.html