2017-05-20 11 views
1
#include <iostream>/File: int-stack.h/
#include <cstdlib> 
using namespace std; 
const int BUFFER SIZE = 100; 
class int stack 
{ 
private: 
int data[BUFFER SIZE]; // Use an array to store data 
int top_index; // Start from 0; -1 when empty 
public: 
int stack(void); // Default constructor 
bool empty(void) const; // Check if the stack is empty 
bool full(void) const; // Check if the stack is full 
int size(void) const; // Give the number of items currently stored 
int top(void) const; // Retrieve the value of the top item 
void push(int); // Add a new item to the top of the stack 
void pop(void); // Remove the top item from the stack 
void insert_at_bottom(int_stack& stack, int item); //adds a new item to the bottom of the stack if the stack is not full. 
}; 

与えられた関数reverse_stack(int_stack &スタック)を実装する必要があります。 これは実装でスタックを使用しても問題はありませんか?

void reverse_stack(int_stack& stack) 
{ 
if (stack.empty()) 
return; 
else 
{ 
int top_item = stack.top(); 
stack.pop(); 
reverse_stack(stack); 
insert_at_bottom(stack, top_item); 
} 
} 

私のソリューションはこれです、再帰を使用してソリューションを提案している、私はそれが正しいことを知りたいと思いました。

void reverse_stack(int_stack& stack){ 
    while(stack.empty() == false){ 
    insert_at_bottom(stack,stack.top()); 
    stack.pop(); 
} 
+0

'pop'pingの前に常に' insert_at_bottom'を呼び出すので、これは永遠に実行されるので、スタックの内容は常に回転します。また、関数に構文エラーがあります。 – ForceBru

+0

適切にテストできるように、コード用のテストハーネスを記述する必要があります。 –

答えて

2

、そうではありません。


あなたの機能:

void reverse_stack(int_stack& stack){ 
    while(stack.empty() == false){ 
    insert_at_bottom(stack,stack.top()); 
    stack.pop(); 
} 

あなただけのスタックをポップした後、ループ内で閉じ括弧が欠落しています。

私の解決策は、これが正しいことを知りたかったのです。

機能をテストするコードを書く必要があります。あなたはそれがうまくいかないことを知っています。あなたは紙を手に入れてコードが何をしているかを描きます。どうしたらいいですか。

あなたの機能をこの(非空のスタックのための)ん:

--- 
|1| 
--- 
|2| 
--- 
|3| 
--- 

挿入底の先頭の要素:

--- 
|2| 
--- 
|3| 
--- 
|1| 
--- 

インサート:

--- 
|1| 
--- 
|2| 
--- 
|3| 
--- 
|1| 
--- 

は先頭の要素をポップ下部の上部要素:

--- 
|2| 
--- 
|3| 
--- 
|1| 
--- 
|2| 
--- 

トップ要素ポップ:

--- 
|3| 
--- 
|1| 
--- 
|2| 
--- 
|3| 
--- 

ポップTOL要素:下部の

--- 
|3| 
--- 
|1| 
--- 
|2| 
--- 

挿入先頭の要素を

--- 
|1| 
--- 
|2| 
--- 
|3| 
--- 

それはこの時点で、あなたの関数を知っていました。それは間違っていた!あなたのスタックは関数を呼び出す前とまったく同じです!

ところで、あなたの機能はいつ終了するのですか?今書かれているとおり、無限ループを実行します!

+1

typoの間違いです。intでなければなりません。top_index; – kdhug886

関連する問題