You are on page 1of 2

WORKSHEET 3

Student Name: Ayush Mishra UID: 22BCS14531


Branch: CSE Section/Group: 22BCS-716 / B

Semester: 3rd Date of Performance: 18.10.2023


Subject Name: Data Structures Subject Code: 22CST-202

Aim :- Stack Operations Given two integer arrays pushed and


popped each with distinct values, return true if this could have been
the result of a sequence of push and pop operations on an initially
empty stack. or false otherwise.
Example 1: Input: pushed =[1,2,3,4,5],
popped =[4,5,3,2,1]
Output: true.

Code:
#include <iostream>
#include <stack>
using namespace std;

bool Sequences(int pushed[], int pushedSize, int popped[], int poppedSize)


{
stack<int> st;
int i = 0;

for (int j = 0; j < pushedSize; j++)


{st.push(pushed[j]);

while (!st.empty() && i < poppedSize && st.top() == popped[i])


{
st.pop();
i++;
}
}

return i == poppedSize;
}

int main() {
int pushed[] = {1, 2, 3, 4, 5};
int popped[] = {5, 4, 3, 2, 1};
int pushedSize = sizeof(pushed) / sizeof(pushed[0]);
int poppedSize = sizeof(popped) / sizeof(popped[0]);

bool result =Sequences(pushed, pushedSize, popped, poppedSize);

if (result)
{
cout << "Output: True" <<endl;
} else {
cout << "Output: false" <<endl;
}

return 0;
}
Output :

Learning Outcomes :

1 Stack Simulation:It iterates through the pushed array, pushing


elements onto the stack and checking if they match the elements in
the popped array

2 Array Size Determination:The code determines the size of the


arrays pushed and popped by dividing the size of the array by the
size of one element. This is a standard way to calculate the size of
an array in C++.

3 Stack Pop and Compare: The while loop inside the for loop iterates
as long as there are elements in the stack and the current element in
the pushed array matches the next element in the popped array.

4 Return Value: This means that all elements were pushed and
popped correctly, and the stack is empty. Otherwise, it returnsfalse.

You might also like