如何反转堆栈

时间:2013-03-26 22:07:52

标签: c++ stack

我有一个任务,我想假装一个堆栈,显示输出然后反转它以显示输出。

它假设看起来像这样

Stack:
262 115 74 26 34 243 22 734 113 121
Stack Reversed:
121 113 734 22 243 34 26 74 115 262

相反,我的出现就像这样

Stack:
262 115 74 26 34 243 22 734 113 121 121 113 734 22 243 34 26 74 115 262
Stack Reversed:

有人可以查看我的代码,看看发生了什么。我已经尝试了很多东西,但无法完成任何工作。

#include <stdio.h>
#include <iostream>

#include "linkedStack.h"

using namespace std;

template <class Type>
void printStack(linkedStackType<Type>& stack);

template <class Type>
void reverseStack(linkedStackType<Type>& stack);

int main(int argc, char **argv)
{
   // Declare stack variables
   linkedStackType<int> stack;

   // Add some data to the stack
   stack.push(121);
   stack.push(113);
   stack.push(734);
   stack.push(22);
   stack.push(243);
   stack.push(34);
   stack.push(26);
   stack.push(74);
   stack.push(115);
   stack.push(262);

   cout << "\nStack:\n   ";
   printStack(stack);

   reverseStack(stack);

   cout << "\nStack Reversed:\n   ";
   printStack(stack);

   cout << "\n\n** Press any key to continue **\n";
   getchar();

   return 0;
}

template <class Type>
void printStack(linkedStackType<Type>& stack)
{
   Type item;
   linkedStackType<Type> tmpStack = stack;

   while (stack.isEmptyStack() == false)
   {
      item = stack.top();
      stack.pop();
      cout << item << " ";
   }

   stack = tmpStack;



 }

template <class Type>
void reverseStack(linkedStackType<Type>& stack)
{
  Type item;
   linkedStackType<Type> tmpStack;

   while (stack.isEmptyStack() == false)
   {
      item = stack.top();
      stack.pop();
      tmpStack.push(item);
   }

   while (tmpStack.isEmptyStack() == false)
   {
      item = tmpStack.top();
      tmpStack.pop();
      stack.push(item);
      cout << item;  

   }

   stack = tmpStack;


   return;
}

4 个答案:

答案 0 :(得分:9)

我不是100%,但我想如果你删除reverseStack的第二个while循环,你的代码就会起作用。

template <class Type>
void reverseStack(linkedStackType<Type>& stack)
{
   Type item;
   linkedStackType<Type> tmpStack;

   while (stack.isEmptyStack() == false)
   {
      item = stack.top();
      stack.pop();
      tmpStack.push(item);
   }

   //while (tmpStack.isEmptyStack() == false)
   //{
   //   item = tmpStack.top();
   //   tmpStack.pop();
   //   stack.push(item);
   //   cout << item;
   //}

   stack = tmpStack;
   return;
}

答案 1 :(得分:1)

您在reverseStack()中有一个无关的打印循环,它会在错误的位置打印值。此外,此打印循环清除您的tmpStack。这解释了结果。

答案 2 :(得分:1)

您的第二个while循环清空tmpStack,但是您将现在为空的堆栈分配给stack,因此您只有一个空堆栈。

答案 3 :(得分:-1)

void sortStack(struct stack **s)  
{  
if (!isEmpty(*s))  
  {  
    int x = pop(s);  
    sortStack(s);  
    sortedInsert(s, x);  
  }  
}  

void sortedInsert(struct stack **s, int x)  
{  
  if (isEmpty(*s) || x > top(*s))  
  {  
    push(s, x);  
    return;  
  }  
int temp = pop(s);  
sortedInsert(s, x);  
push(s, temp);  
}  
相关问题