"description":
This article is a C + + replication of the topic of "sequencing another stack with one stack" in the first chapter of the Programmer's Interview code guide by Zhoecheng.
This article only contains the problem description, the implementation of C + + code and simple ideas, not including the explanation, the specific problem analysis please refer to the original book.
Thank Zhoecheng teacher for his support.
"title":
The type of element in a stack is shaped, and now you want to sort the stack from top to bottom, and only apply a stack. In addition, you can apply for new variables, but you cannot request additional data structures. How do I finish sorting?
"Ideas":
I do not know that everyone has played nine series of wood, feeling the idea of solving the problem is quite similar; this solution and the insertion sort also have a certain similarity.
"Compile environment":
CentOS6.7 (x86_64)
GCC 4.4.7
"Implementation":
Implementing and testing the code
/** File Name: SortStack.cpp * * Abstract: Use one stack for the reverse of another stack*/#include<stack>#include<iostream>using namespacestd;voidSortstack (stack<int> &s) {Stack<int>Auxs; while(!S.empty ()) { intTMP =S.top (); S.pop (); while(!auxs.empty () && auxs.top () <tmp) {S.push (Auxs.top ()); Auxs.pop (); } auxs.push (TMP); } while(!Auxs.empty ()) {S.push (Auxs.top ()); Auxs.pop (); }}intMain () {intA[] = {3,4,5,1,2,1}; Stack<int>s; inti; for(i=0;i<6; i++) {s.push (a[i]); } cout<<"The Datum of the stack before sorting are:"<<Endl; for(i=0;i<6; i++) {cout<< s.top () <<Endl; S.pop (); } for(i=0;i<6; i++) {s.push (a[i]); } cout<<"The Datum of the stack after sorting is:"<<Endl; Sortstack (s); for(i=0;i<6; i++) {cout<< s.top () <<Endl; S.pop (); } return 0;}
View Code
Note:
Reprint please indicate the source;
Reprint please indicate source idea from Zhoecheng Teacher's "Programmer Code Interview Guide".
Use one stack to sort another stack