上机3.2
2、编写一个函数SelectItem( Stack & s, int n) ,要求利用堆栈来查找n在栈中第一次出现的位置,并将该位置元素移至栈顶,同时其他元素次序不变。
注:栈类用了之前定义的
1 //============================================================================ 2 // Name : shangji3.2.cpp 第三次上机第二题 3 // Author : menglei 4 // Version : 2012.10.30 5 // Copyright : Your copyright notice 6 // Description : Hello World in C++, Ansi-style 7 //============================================================================ 8 9 /** 10 * 2、编写一个函数SelectItem( Stack & s, int n) , 11 * 要求利用堆栈来查找n在栈中第一次出现的位置, 12 * 并将该位置元素移至栈顶,同时其他元素次序不变。 13 */ 14 #include <iostream> 15 using namespace std; 16 17 //template<class T> 18 class mStack{ //call a stack 19 private: 20 int size; 21 int *stackArray; 22 int top; 23 public: 24 mStack(){ 25 size = 100; 26 top = -1; 27 stackArray = new int[100]; 28 } 29 int pop(){ 30 if(top==-1){ 31 cout<<"stack is empty ,can't pop!"<<endl; 32 return NULL; //返回NULL会有问题,但编译能通过 33 } 34 top--; 35 return stackArray[top]; 36 } 37 int push(int value){ 38 if(top==size){ 39 cout<<"stack is full ! can't push !"<<endl; 40 return -1; 41 } 42 stackArray[top++]= value; 43 return 1; 44 } 45 int getTop(void){ 46 if(top==-1){ 47 cout<<"stack is empty! "<<endl; 48 return NULL; 49 } 50 return stackArray[top-1]; 51 } 52 int isEmpty(){ 53 if(top==-1) 54 return 1; 55 return 0; 56 } 57 58 }; 59 int main() { 60 mStack m; 61 m.push(1); 62 m.push(2); 63 m.push(3); 64 m.push(4); 65 m.push(5); 66 m.push(6); 67 m.push(7); 68 69 mStack temp; 70 int t; 71 int count = 1; 72 t= m.pop(); 73 while(t!=3) //比如查找3 74 { 75 //cout<<"t="<<t<<endl; 76 temp.push(t); 77 t = m.pop(); 78 count++; 79 } 80 //找到了 81 int tempN = t; 82 cout<<"元素3的距离栈顶的位置为:"<<count<<endl; 83 while(!temp.isEmpty()){ 84 m.push(temp.pop()); 85 } 86 m.push(tempN); 87 //下面是检验 88 cout<<"改变后的栈的顺序为:"<<endl; 89 while(!m.isEmpty()){ 90 cout<<m.getTop()<<endl; 91 m.pop(); 92 } 93 return 0; 94 } 95
运行结果:
转载文章请注明出处: http://www.cnblogs.com/menglei/