本文共 1287 字,大约阅读时间需要 4 分钟。
目的:使用STL中的vector模板,设计并实现顺序表应用场合的一些简单算法设计。
应用1:试设计一个算法,用尽可能少的辅助空间将顺序表中前 m 个元素和后 n 个元素进行互换,即将线性表(a1,a2,…,am,b1,b2,…,bn) 改变成(b1,b2,…,bn,a1,a2,…,am)。
参考函数原型:template
void Exchange( vector &A,int m );// 本算法实现顺序表中前 m 个元素和后 n 个元素的互换第一行:待处理顺序表的长度
第二行:待处理顺序表的数据元素(数据元素之间以空格分隔)
第三行:逆置位置m
第一行:待处理顺序表的遍历结果
第二行:逆置结果
1013 5 27 9 32 123 76 98 54 875
13 5 27 9 32 123 76 98 54 87 123 76 98 54 87 13 5 27 9 32
void realExchange(vector&A,int left,int right){ //swap reverse the element between left and right Elemtype temp; while(left <= eight) { temp = A[left]; A[left] = A[right]; A[left] = temp; left ++; right --; }}template void Exchange(vector & A,int m){ //reverse the whole vector realExchange(A,0,A.size()); //reverse the element between 0 and m realExchange(A,0,m); //reverse the elements between m and A.size() realExchange(A,m,A.size());}
转载地址:http://jwwvb.baihongyu.com/