C++ 使用一个栈实现另一个栈的排序

来源:互联网 发布:淘宝买k粉暗语 编辑:程序博客网 时间:2024/04/27 17:09
#include <iostream>
#include <stack>


void print(std::stack<int> &stk);
void sort(std::stack<int> &stack);


int main()
{
std::stack<int> stk;         //help 栈底存储数值比较大的, stk栈底存储比较小的

int arr[8] = { 2, 5, 1, 15, 19, 11, 25, 17 };
int *beg = std::begin(arr);
int *end = std::end(arr);


while (beg != end)
{
stk.push(*beg++);
}


std::cout << "Before sort: " << std::endl;
print(stk);
beg = std::begin(arr);
while (beg != end)
{
stk.push(*beg++);
}


sort(stk);
std::cout << "After sort: " << std::endl;
print(stk);


system("pause");
return 0;
}


void print(std::stack<int> &stk)
{
while (!stk.empty())
{
std::cout << stk.top() << std::endl;
stk.pop();
}
}


void sort(std::stack<int> &stack)
 {
if (stack.empty())
{
return;
}


std::stack<int> help;
int cur = 0;


while (!stack.empty())
{
cur = stack.top();
stack.pop();
while (!help.empty())
{
if (cur > help.top())
{
stack.push(help.top());
help.pop();
}
else
break;
}
help.push(cur);
}


while (!help.empty())
{
stack.push(help.top());
help.pop();
}
}
阅读全文
0 0
原创粉丝点击