ページ 11

An array-based stack

Posted: 2012年10月09日(火) 18:00
by An array-based stack
ここから先が書けません。どうすれば正しいコードになりますか?

In this question, we are going to implement a class Stack. We will use an array as a container for the elements of the stack. Elements of the stack will be of type 'int'.

Create the files: "Stack.h", "Stack.cpp" and "test_stack.cpp".

"Stack.h" will contain the definition of the class Stack.
"Stack.cpp" will contain the implementation of the methods of the class Stack.
"test_stack.cpp" will contain the main function that will test our created class.

Step 1: Type the following code in the file "Stack.h":

コード:

// Stack.h
#ifndef STACK_H
#define STACK_H

class Stack {
public:
  Stack(int N) : size(0), max_size(N), top(-1), data(new int[N]) {}
  ~Stack() { delete[] data; }

  // push the element el in the stack
  // print an error message if trying to push an element in a full stack
  void push(int el); 

  // pop the element on top of the stack and return it
  // print an error message if trying to pop from 
  //   an empty stack and returns a dummy int
  int pop();
   
  // return true if stack is full 
  bool is_full(); 
  
  // return true if stack is empty
  bool is_empty(); 
  
  // return the num of elements in the stack
  int num_elements(); 

private:
  int size;
  int max_size;
  // top is the index to the topmost element of the stack
  int top; 
  int* data;
};

#endif // STACK_H
Step 2: Implement the methods push, pop, is_full, is_empty and num_elements in the file "Stack.cpp"

Step 3: Type the following code in the file "test_stack.cpp". You will use this code to test your stack implementation.

コード:

// test_stack.cpp
#include <iostream>
#include "Stack.h"

int main(void) {
  Stack s(5);

  if (s.is_empty()) std::cout << "Empty stack" << std::endl;

  s.push(2);
  s.push(5);
  s.push(7);
  s.push(9);
  s.push(9);
  
  if (s.is_full()) std::cout << "full stack" << std::endl;

  std::cout << "Num of elements: " << s.num_elements() << std::endl;

  int t;
  while (!s.is_empty()) {
   t = s.pop();         
   std::cout << t << std::endl;
   std::cout << "Num of elements: " << s.num_elements() << std::endl;
  }
}

Re: An array-based stack

Posted: 2012年10月09日(火) 18:09
by softya(ソフト屋)
「Static members • C言語交流フォーラム ~ mixC++ ~」
http://dixq.net/forum/viewtopic.php?f=3&t=11638
と同じ方だと思いますが名前をちゃんと決めて頂けるようにお願いします。
これはフォーラムルールとなっております。 http://dixq.net/board/board.html
その他にも読んで頂きたい所が沢山あります。

【補足】
こっちの問題のままですね。
「Exercise 2」
http://web-ext.u-aizu.ac.jp/~fayolle/te ... e/ex2.html

当掲示板は課題の丸投げは禁止させて頂いています。
かならず、ご自分で書いたコードも投稿なさってください。
どうしても分からない時は解き方についてご質問ください。