Docsity

C++ Program for Infix to Postfix Conversion using Stack (Linked List), Assignments of Data Structures and Algorithms

Toggle sidebar
bg1
1.Write a C++ program to implement infix to postfix
using stack. (linked list)
Ans- #include<bits/stdc++.h>
using namespace std;
int prec(char c)
{
if(c == '^')
return 3;
else if(c == '*' || c == '/')
return 2;
else if(c == '+' || c == '-')
return 1;
else
return -1;
}
void infixToPostfix(string s)
{
std::stack<char> st;
st.push('N');
int l = s.length();
string ns;
for(int i = 0; i < l; i++)
{
if((s[i] >= 'a' && s[i] <= 'z')||(s[i] >= 'A' && s[i] <= 'Z'))
ns+=s[i];
else if(s[i] == '(')
pf3
pf4

Partial preview of the text

Download C++ Program for Infix to Postfix Conversion using Stack (Linked List) and more Assignments Data Structures and Algorithms in PDF only on Docsity!

1.Write a C++ program to implement infix to postfix

using stack. (linked list)

Ans- #include<bits/stdc++.h>

using namespace std; int prec(char c) { if(c == '^') return 3; else if(c == '*' || c == '/') return 2; else if(c == '+' || c == '-') return 1; else return -1; } void infixToPostfix(string s) { std::stack st; st.push('N'); int l = s.length(); string ns; for(int i = 0; i < l; i++) { if((s[i] >= 'a' && s[i] <= 'z')||(s[i] >= 'A' && s[i] <= 'Z')) ns+=s[i]; else if(s[i] == '(')

st.push('('); else if(s[i] == ')') { while(st.top() != 'N' && st.top() != '(') { char c = st.top(); st.pop(); ns += c; } if(st.top() == '(') { char c = st.top(); st.pop(); } } else{ while(st.top() != 'N' && prec(s[i]) <= prec(st.top())) { char c = st.top(); st.pop(); ns += c; } st.push(s[i]); } }