Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Stek.h
- #pragma once
- #include <iostream>
- using namespace std;
- class Stek {
- char* niz;
- int top;
- int numOfElements;
- public:
- Stek(int n) {
- numOfElements = n;
- niz = new char[numOfElements]();
- top = -1;
- }
- void push(char ch) {
- if (top + 1 == numOfElements) {
- cout << "Stek je pun!\n";
- return;
- }
- top++;
- niz[top] = ch;
- }
- char pop() {
- if (top >= 0) {
- char vrati = niz[top];
- top--;
- return vrati;
- }
- else
- cout << "Stek je prazan!\n";
- }
- void infix2postfix(char* izraz) {
- int i = 0;
- while (izraz[i] != '\0') {
- if (izraz[i] != '+' && izraz[i] != '-' && izraz[i] != '*' && izraz[i] != '/' && izraz[i] != '^' && izraz[i] != '(' && izraz[i] != ')') {
- cout << izraz[i];
- i++;
- continue;
- }
- if (izraz[i] == '(') {
- push('(');
- i++;
- continue;
- }
- if (izraz[i] == ')') {
- char ch = pop();
- while (ch != '(') {
- cout << ch;
- ch = pop();
- }
- i++;
- continue;
- }
- if (izraz[i] != '+' || izraz[i] != '-' || izraz[i] != '*' || izraz[i] != '/' || izraz[i] != '^') {
- if (top < 0) {
- push(izraz[i]);
- i++;
- continue;
- }
- if (!stepenOp(niz[top], izraz[i])) {
- cout << pop();
- while (!stepenOp(niz[top], izraz[i]) && numOfElements > 0) {
- cout << pop();
- }
- push(izraz[i]);
- i++;
- continue;
- }
- push(izraz[i]);
- }
- i++;
- }
- while (top >= 0) {
- cout << pop();
- }
- cout << endl;
- }
- private:
- bool stepenOp(char x, char y) {
- if (x == '-' || x == '+') {
- if (y == '+' || y == '-')
- return 0;
- else
- return 1;
- }
- if (x == '*' || x == '/') {
- if (y == '+' || y == '-' || y == '*' || y == '/')
- return 0;
- else
- return 1;
- }
- if (x == '^') {
- return 0;
- }
- return 1;
- }
- };
- // main
- #pragma once
- #include "stek.h"
- void main() {
- char string[200];
- cout << "Napisite izraz za prebacivanje:\n";
- gets_s(string);
- Stek a(10);
- a.infix2postfix(string);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement