Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Program calculates postfix expressions #12

Open
wants to merge 11 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions hw6/postfix expression/postfix expression.sln
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.27703.1
MinimumVisualStudioVersion = 10.0.40219.1
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "postfix expression", "postfix expression\postfix expression.vcxproj", "{71E3947C-0B74-4DAA-9648-0CF33E3270DD}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|x64 = Debug|x64
Debug|x86 = Debug|x86
Release|x64 = Release|x64
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{71E3947C-0B74-4DAA-9648-0CF33E3270DD}.Debug|x64.ActiveCfg = Debug|x64
{71E3947C-0B74-4DAA-9648-0CF33E3270DD}.Debug|x64.Build.0 = Debug|x64
{71E3947C-0B74-4DAA-9648-0CF33E3270DD}.Debug|x86.ActiveCfg = Debug|Win32
{71E3947C-0B74-4DAA-9648-0CF33E3270DD}.Debug|x86.Build.0 = Debug|Win32
{71E3947C-0B74-4DAA-9648-0CF33E3270DD}.Release|x64.ActiveCfg = Release|x64
{71E3947C-0B74-4DAA-9648-0CF33E3270DD}.Release|x64.Build.0 = Release|x64
{71E3947C-0B74-4DAA-9648-0CF33E3270DD}.Release|x86.ActiveCfg = Release|Win32
{71E3947C-0B74-4DAA-9648-0CF33E3270DD}.Release|x86.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {FA9D9EDC-47CF-4A60-8B4C-25B0FAC8F792}
EndGlobalSection
EndGlobal
13 changes: 13 additions & 0 deletions hw6/postfix expression/postfix expression/Element.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
#include "Element.h"

Element::Element(int data = 0)
{
this->data = data;
this->next = nullptr;
}

Element::~Element()
{
this->data = 0;
this->next = nullptr;
}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Деструктор не нужен :)

9 changes: 9 additions & 0 deletions hw6/postfix expression/postfix expression/Element.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
#pragma once

struct Element
{
Element(int data);

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

explicit

~Element();

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Деструктор не нужен :)

int data;
Element* next;
};
57 changes: 57 additions & 0 deletions hw6/postfix expression/postfix expression/Postfix.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
#include "Postfix.h"
#include "Stack.h"

bool isOperator(char symbol);
int performOperation(char symbol, int firstNum, int secondNum);

int fromPostfixToResult(string const & str)
{
Stack s;
int sizeOfStr = (int)str.size();

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Зачем каст к инту, она ж возвращает size_t небось, можно было for (size_t i = 0; i < sizeOfStr; ++i)

for (int i = 0; i < sizeOfStr; ++i)
{
if (!isOperator(str[i]))
{
char number = str[i];
int numberInInt = atoi(&number);
s.push(numberInInt);
}
else
{
int num2 = s.peek();

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Хотелось бы, чтобы оно не делало странное на некорректных тестах, а адекватно ругалось

s.pop();
int num1 = s.peek();
s.pop();
int resultOfOperation = performOperation(str[i], num1, num2);
s.push(resultOfOperation);
}
}
int result = s.peek();
return result;

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Можно просто return s.peek();, хотя как у Вас отлаживаться удобнее.

}

bool isOperator(char symbol)
{
return (symbol == '+' || symbol == '-' || symbol == '*' || symbol == '/');
}

int performOperation(char symbol, int firstNum, int secondNum)
{
int result = 0;
switch (symbol)
{
case '+':
result = firstNum + secondNum;
break;
case '-':
result = firstNum - secondNum;
break;
case '*':
result = firstNum * secondNum;
break;
case '/':
result = firstNum / secondNum;
break;
}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

А если ни один из случаев?

return result;
}
7 changes: 7 additions & 0 deletions hw6/postfix expression/postfix expression/Postfix.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
#pragma once
#include <iostream>
#include <string>

using namespace std;

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Нельзя using namespace в .h-никах


int fromPostfixToResult(string const & str);
65 changes: 65 additions & 0 deletions hw6/postfix expression/postfix expression/Stack.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
#include "Stack.h"
#include "Element.h"

Stack::Stack()
{
head = nullptr;
}

Stack::~Stack()
{
auto* temp = head;

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Её можно было прямо внутри цикла объявить

while (!isEmpty())
{
temp = head;
head = temp->next;
temp->next = nullptr;
delete temp;
temp = nullptr;

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Это не нужно :)

}
}

void Stack::push(int data)
{
auto* newElement = new Element(data);
if (!isEmpty())
{
newElement->next = head;
}
head = newElement;
}

int Stack::pop()
{
if (!isEmpty())
{
auto* temp = head->next;
head->next = nullptr;
delete head;
head = nullptr;
head = temp;

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Карго-культ же :) head = nullptr тут точно не нужен. Хотя с точки зрения методологии может быть хорошей идеей всегда занулять удаляемые переменные, чтобы случайно не забыть, но код непомерно растёт, так что не знаю. В принципе, можно не править :)

return 0;
}
else
{
return -1;
}
}

int Stack::peek()
{
if (!isEmpty())
{
return head->data;
}
else
{
cout << "Stack is empty\n";
return -1;
}
}

bool Stack::isEmpty()
{
return head == nullptr;
}
28 changes: 28 additions & 0 deletions hw6/postfix expression/postfix expression/Stack.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
#pragma once
#include <iostream>

using namespace std;

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Нельзя :)


struct Element;

struct Stack
{
// �����������
Stack();
// ����������

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Лучше добавлять пустую строку между методами:

struct Stack
{
    // конструктор
    Stack();

    // деструктор
    ~Stack();

~Stack();
// ����������� �����������

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Невидимый конструктор :)

// �������� ������������

// ���������� �������� � ������
void push(int data);
// �������� �������� �� ������
int pop();

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Может, лучше bool возвращать, раз оно только 0 или -1?

// ���������� �� �������� �������
int peek();

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

int peek() const;, оно не меняет состояние объекта

// ��������� �������� �� ���� ������
bool isEmpty();

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bool isEmpty() const;, оно не меняет состояние объекта

private:
Element * head;
};
17 changes: 17 additions & 0 deletions hw6/postfix expression/postfix expression/main.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
#include <iostream>
#include <string>
#include "Postfix.h"

using namespace std;

int main()
{
string str;
cout << "Input string" << endl;
cin >> str;
cout << "result is " << fromPostfixToResult(str) << endl;


system("pause");

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Нельзя :)

return 0;
}
131 changes: 131 additions & 0 deletions hw6/postfix expression/postfix expression/postfix expression.vcxproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<VCProjectVersion>15.0</VCProjectVersion>
<ProjectGuid>{71E3947C-0B74-4DAA-9648-0CF33E3270DD}</ProjectGuid>
<RootNamespace>postfixexpression</RootNamespace>
<WindowsTargetPlatformVersion>10.0.17134.0</WindowsTargetPlatformVersion>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v141</PlatformToolset>
<CharacterSet>MultiByte</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v141</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>MultiByte</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v141</PlatformToolset>
<CharacterSet>MultiByte</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v141</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>MultiByte</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup />
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<SDLCheck>true</SDLCheck>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<SDLCheck>true</SDLCheck>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="Element.cpp" />
<ClCompile Include="main.cpp" />
<ClCompile Include="Postfix.cpp" />
<ClCompile Include="Stack.cpp" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="Element.h" />
<ClInclude Include="Postfix.h" />
<ClInclude Include="Stack.h" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>
Loading