constint defaultSize = 100; template <classType> classSeqList { Type *data; //顺序表存储数组 int MaxSize; //最大允许长度 int last; //当前最后元素下标 public: SeqList ( int sz = defaultSize ); ~SeqList ( ) { delete [ ] data; } intLength( )const{ return last+1; } intFind( Type & x )const; intIsIn( Type & x ); intInsert( Type & x, int i ); intRemove( Type & x ); intNext( Type & x ); intPrior( Type & x ); intIsEmpty( ){ return last == -1; } intIsFull( ){ return last == MaxSize-1; } Type Get( int i ){ return i < 0 || i > last? NULL : data[i]; } }
算法
搜索
1 2 3 4 5 6 7 8 9 10
template <classType> int SeqList<Type>::Search ( Type & x ) const { //搜索函数:在表中从前向后顺序查找 x int i = 0; while ( i <= last && data[i] != x ){ i++; } if ( i > last ) return-1; elsereturn i; }
最好:1
最坏:n
平均:n1(1+2+…+n)=21+n O(n)
插入
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
template <classType> int SeqList<Type>::Insert ( Type & x, int i ){ //在表中第 i 个位置插入新元素 x if ( i < 0 || i > last+1 || last == MaxSize-1 ){ return0; //插入不成功 } else { last++; for (int j = last; j > i; j--){ data[j] = data[j -1]; } data[i] = x; return1; //插入成功 } }
最好:0
最坏:n
平均:n+11(n+…+1+0)=2n O(n)
删除
1 2 3 4 5 6 7 8 9 10 11 12 13
template <classType> int SeqList<Type>::Remove ( Type & x ) { //在表中删除已有元素 x int i = Find (x); //在表中搜索 x if ( i >= 0 ) { last-- ; for ( int j = i; j <= last; j++ ){ data[j] = data[j+1]; } return1; //成功删除 } return0; //表中没有 x }
最好:0
最坏:n-1
平均:n1((n−1)+…+1+0)=2n−1 O(n)
单链表
特点
每个元素有结点(Node)构成
线性结构
结点可以不连续存储
表可扩充
实现
1 2 3 4 5 6 7 8 9 10
structListNode { //链表结点类 int data; ListNode * link; };