0% found this document useful (0 votes)
15 views

Lab02 Stacks

Uploaded by

funcosy13
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

Lab02 Stacks

Uploaded by

funcosy13
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

Lab02- Stack

1. Implement a stack with C++ code:


a. Use Linked List
b. Include functions push, pop, peek, isEmpty
c. Can use any data type

#include <iostream>
// Function to check if the stack is empty
// Define a Node structure for the stack bool isEmpty() {
template <typename T> return top == nullptr;
struct Node { }
T data;
Node* next; // Function to get the top element of the stack without
}; popping it
T peek() {
// Define the Stack class using templates if (isEmpty()) {
template <typename T> throw std::out_of_range("Stack is empty");
class Stack { }
private: return top->data;
Node<T>* top; }

public: // Destructor to free memory when the stack is destroyed


// Constructor to initialize an empty stack ~Stack() {
Stack() { while (!isEmpty()) {
top = nullptr; Node<T>* temp = top;
} top = top->next;
delete temp;
// Function to push an element onto the stack }
void push(T value) { }
Node<T>* newNode = new Node<T>; };
newNode->data = value;
newNode->next = top; int main() {
top = newNode; Stack<int> intStack;
} intStack.push(42);
// Popping and displaying elements from the stacks
//Function to pop and return the top element from the stack std::cout << "Popped from intStack: " << intStack.pop() <<
T pop() { std::endl;
if (isEmpty()) { }
throw std::out_of_range("Stack is empty");
}
T value = top->data;
Node<T>* temp = top;
top = top->next;
delete temp;
return value;
}
Push to stack Pop from Stack

2. Given an expression string exp, write a program to examine whether the pairs and the orders of “{“, “}”,
“(“, “)”, “[“, “]” are correct in the given expression.

Input: exp = “[()]{}{[()()]()}”, Output: Balanced

Input: exp = “[(])”, Output: Not Balanced

a. Use stack you defined above


b. Algorithm: The idea is to put all the opening brackets in the stack. Whenever you hit a closing
bracket, search if the top of the stack is the opening bracket of the same nature. If this holds
then pop the stack and continue the iteration. In the end if the stack is empty, it means all
brackets are balanced or well-formed. Otherwise, they are not balanced.

// Function to check if brackets are balanced


bool bracketsBalanced(std::string expr){
// Declare a stack to hold the previous brackets.
Stack<char> st;
for (int i = 0; i < expr.length(); i++) {
if (st.isEmpty()) {
// If the stack is empty just push the current bracket
st.push(expr[i]);
}
else if ((st.peek() == '(' && expr[i] == ')')
|| (st.peek() == '{' && expr[i] == '}')
|| (st.peek() == '[' && expr[i] == ']')) {

// If we found any complete pair of bracket then pop


st.pop();
}
else {
st.push(expr[i]);
}
}
if (st.isEmpty()) {
// If stack is empty return true
return true;
}
return false;
}
3. Change a decimal number to any base 2-9, or 16
a. Use stack in question 1
b. Check the algorithm in the slides (stack)

void convertBase(int n, int b) {


std::string digitChar = "0123456789ABCDEF“;
Stack<int> st;
do {
//Tính chữ số bên phải nhất,đẩy vào stack
st.push(n % b);
n /= b; // Thay n = n/b để tính tiếp
} while (n != 0); // Lặp đến khi n = 0

while(!st.isEmpty() ){
//Rút lần lượt từng phần tử của stack
n = st.pop();
//chuyển sang dạng ký tự và in kết quả
std::cout<<digitChar[n];
}
}
4. Implement a C/C++ code to convert an infix expression to postfix, for example, input an infix
expression (20+5)/5+(7-3)*100  20 5 + 5 / 7 3 - 100 * +
Algorithm:
1. Scan the infix expression from left to right.
2. If the scanned character is an operand, output to postfix.
3. Else,
1. If the precedence of the scanned operator is greater than the precedence of the operator in the
stack [or the stack is empty, or stack contain ‘)’], push it to stack.
2. Else, pop the operator to postfix from the stack until the precedence of the scanned operator is
less-equal to the precedence of the operator residing on the top of the stack. Push the scanned
operator to the stack.
4. If the scanned character is an ‘(‘, push it to the stack.
5. If the scanned character is an ‘)’, pop and output from the stack until an ‘(‘ is encountered.
6. Repeat steps 2-6 until infix expression is scanned.
7. Pop and output until the stack is empty.
// Function to return precedence of operators
int priority(char c){
if (c == '^')
return 3;
else if (c == '/' || c == '*')
return 2;
else if (c == '+' || c == '-')
return 1;
else
return -1;
}

// The main function to convert infix expression


// to postfix expression
string infixToPostfix(string infix){

Stack<char> st;
string postfix;

for (int i = 0; i < infix.length(); i++) {


char c = infix[i];
if (infix[i] == ' ' || infix[i] == '\t') continue;
if (isdigit(infix[i])) {
int num = 0;

// Extract full number


while (isdigit(infix[i])) {
num = num * 10 + (int)(infix[i] - '0');
i++;
}
i--;
postfix = postfix + to_string(num) + " ";
}

// If the scanned character is an


// ‘(‘, push it to the stack.
else if (c == '(') st.push('(');

// If the scanned character is an ‘)’,


// pop and add to output string from the stack
// until an ‘(‘ is encountered.
else if (c == ')') {
while (st.peek() != '(') {
postfix = postfix + st.pop() + " ";
}
st.pop();
}

// If an operator is scanned
else {
while (!st.isEmpty()
&& priority(infix[i]) <= priority(st.peek())) {
postfix = postfix + st.pop() + " ";
}
st.push(c);
}
}

// Pop all the remaining elements from the stack


while (!st.isEmpty())
postfix = postfix + st.pop() + " ";
return postfix;
}

5. Evaluate postfix expression, for example 20 5 + 5 / 7 3 – 100 * +  405


a. Use defined stack above
b. Algorithm:
• Scan each character from right to left
– Step 1: If the character is an operand, push it to Stack
– Step 2: If the character is an operator
• Pop two elements from the Stack.
• Perform the operator, and push the result back to the Stack
– Step 3: read the next character and go to Step 1
• The Result is stored at the top of the Stack
// The main function that returns value of a given postfix }
expression
int evaluatePostfix(string exp){ // If the scanned character is an operator, pop two
// Create a stack of capacity equal to expression size // elements from stack apply the operator
Stack<int> st; else {
int i; int val1 = st.pop();
int val2 = st.pop();
// Scan all characters one by one
for (i = 0; exp[i]; ++i) { switch (exp[i]) {
// If the character is blank space then continue case '+':
if (exp[i] == ' ') continue; st.push(val2 + val1);
break;
// If the scanned character is an case '-':
// operand (number here),extract the full number st.push(val2 - val1);
// Push it to the stack. break;
else if (isdigit(exp[i])) { case '*':
int num = 0; st.push(val2 * val1);
break;
// Extract full number case '/':
while (isdigit(exp[i])) { st.push(val2 / val1);
num = num * 10 + (int)(exp[i] - '0'); break;
i++; }
} }
i--; }
return st.peek();
// Push the element in the stack }
st.push(num);

You might also like