5 / 5 / 1
Регистрация: 09.09.2012
Сообщений: 227
1

Программа, которая переводит арифметические выражения в postfix notation используя Stack

10.03.2013, 13:34. Показов 499. Ответов 0
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Помогите, пожалуйста,
разабраться как написать программу, которая переводит арифметические выражения в postfix notation используя Stack.

Input - это числа и арифм. выражения:
[2 3 + 7 *
2 6 + 9 /
14 2 + 160 /
99 2 + 50 / 24 -
100 4 / 3 * 20 +
14 3 * 19 + 12 / 3 + 7 *
23 7 + 10 * 14 + 19 - 22 * 16 /]

Программа должна:
- читать каждую линию отдельно из файла и проводить расчёт значения;
- выводить это линию и результат на экран;
- использовать шаблон - класс Stack;
- читать файл как character arrays или into Strings;

Нужна помощь как правильно написать:
чтобы читала из файла правильно.

Header для Stack:
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
// FILE: stack2.h 
// TEMPLATE CLASS PROVIDED: stack<Item> (a stack of items)
//   The template parameter, Item, is the data type of the items in the stack,
//   also defined as stack<Item>::value_type.
//   It may be any of the C++ built-in types (int, char, etc.), or a class
//   with a default constructor, a copy constructor, and an assignment
//   operator. The definition stack<Item>::size_type is the data type of
//   any variable that keeps track of how many items are in a stack.
//
// CONSTRUCTOR for the stack<Item> template class:
//   stack( )
//     Postcondition: The stack has been initialized as an empty stack.
//
// MODIFICATION MEMBER FUNCTIONS for the stack<Item> class:
//   void push(const Item& entry)
//     Precondition: size( ) < CAPACITY.
//     Postcondition: A new copy of entry has been pushed onto the stack.
//
//   void pop( )
//     Precondition: size( ) > 0.
//     Postcondition: The top item of the stack has been removed.
//
// CONSTANT MEMBER FUNCTIONS for the stack<Item> class:
//   bool empty( ) const
//     Postcondition: Return value is true if the stack is empty.
//
//   size_type size( ) const
//     Postcondition: Return value is the total number of items in the stack.
//
//   Item top( ) const
//     Precondition: size( ) > 0.
//     Postcondition: The return value is the top item of the stack (but the
//     stack is unchanged. This differs slightly from the STL stack (where
//     the top function returns a reference to the item on top of the stack).
//
// VALUE SEMANTICS for the stack<Item> class:
//   Assignments and the copy constructor may be used with stack<Item>
//   objects.
//
// DYNAMIC MEMORY USAGE by the stack<Item> template class:
//   If there is insufficient dynamic memory, then the following functions
//   throw bad_alloc:
//   the copy constructor, push, and the assignment operator.
 
#ifndef MAIN_SAVITCH_STACK2_H
#define MAIN_SAVITCH_STACK2_H
#include <cstdlib>   // Provides NULL and size_t
#include "node2.h"   // Node template class from Figure 6.5 on page 308
 
namespace main_savitch_7B
{
    template <class Item>
    class stack
    {
    public:
        // TYPEDEFS 
        typedef std::size_t size_type;
        typedef Item value_type;
        // CONSTRUCTORS and DESTRUCTOR
        stack( ) { top_ptr = NULL; }
        stack(const stack& source);
        ~stack( ) { list_clear(top_ptr); }
        // MODIFICATION MEMBER FUNCTIONS
        void push(const Item& entry);
        void pop( );
        void operator =(const stack& source);
        // CONSTANT MEMBER FUNCTIONS
        size_type size( ) const
        { return main_savitch_6B::list_length(top_ptr); }
        bool empty( ) const { return (top_ptr == NULL); }
        Item top( ) const;
    private:
        main_savitch_6B::node<Item> *top_ptr;  // Points to top of stack
    };
}
 
#include "stack2.template" // Include the implementation 
#endif
implementation file:
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
// FILE: stack2.template
// TEMPLATE CLASS IMPLEMENTED: stack<Item> (see stack2.h for documentation)
// This file is included in the header file, and not compiled separately.
// INVARIANT for the stack class:
//   1. The items in the stack are stored in a linked list, with the top of the
//      stack stored at the head node, down to the bottom of the stack at the
//      final node.
//   2. The member variable top_ptr is the head pointer of the linked list.
 
#include <cassert>  // Provides assert
#include "node2.h"  // Node template class
 
namespace main_savitch_7B
{
    template <class Item>
    stack<Item>::stack(const stack<Item>& source) 
    // Library facilities used: node2.h
    {
        main_savitch_6B::node<Item> *tail_ptr; // Needed for argument of list_copy
 
        list_copy(source.top_ptr, top_ptr, tail_ptr);
    }
 
    template <class Item>
    void stack<Item>::push(const Item& entry) 
    // Library facilities used: node2.h
    {
        list_head_insert(top_ptr, entry);
    }
 
    template <class Item>
    void stack<Item>::pop( )
    // Library facilities used: cassert, node2.h
    {
        assert(!empty( ));
        list_head_remove(top_ptr);
    }
    
    template <class Item>
    void stack<Item>::operator =(const stack<Item>& source) 
    // Library facilities used: node2.h
    {
        main_savitch_6B::node<Item> *tail_ptr; // Needed for argument of list_copy
 
        if (this == &source) // Handle self-assignment
            return;
 
        list_clear(top_ptr);
        list_copy(source.top_ptr, top_ptr, tail_ptr);
    }
 
    template <class Item>
    Item stack<Item>::top( ) const 
    // Library facilities used: cassert
    {
        assert(!empty( ));
        return top_ptr->data( );
    }
}
Помогите, пожалуйста, ну очень нужно.
0
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
10.03.2013, 13:34
Ответы с готовыми решениями:

Программа которая переводит из 16-ую в 10-ую с.с.
Здравствуйте, помогите плиз. Эта программа переводит десятичное число в шестнадцатеричное...

Используя стек, определить функцию, которая переводит выражение в префиксную форму
Есть задание - Используя стек, определить функцию, которая переводит выражение, записанное в...

Составить из х цифр у число к используя арифметические выражения
Помогите пожалуйста сделать задачку на Prolog. (если это возможно) Даны три числа: х, у, к....

Программа, которая переводит числа в слова
Здрасти всем. Есть код: #include &lt;conio.h&gt; #include &lt;stdio.h&gt; #include &lt;iostream&gt; #include...

0
10.03.2013, 13:34
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
10.03.2013, 13:34
Помогаю со студенческими работами здесь

Программа, которая переводит число из 2-й системы счисления в 16-ую
Программа, которая переводит число из 2-й системы счисления в 16-ую.

Программа которая переводит из 2ой системы в 10ую
Создать программу которая переводит из двоичной системы в десятичную. P.S вообще то я знаю как...

Программа, которая переводит числа из 10 системы в другие
Программа, которая переводит числа из 10 системы в другие. Мы прошли while, for. Как-то замудрено...

Вывести большее из двух чисел используя только арифметические выражения
#include&lt;iostream&gt; #include&lt;stdio.h&gt; #include&lt;math.h&gt; int main() { using namespace std; int...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
1
Ответ Создать тему
Опции темы

КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2023, CyberForum.ru