0% found this document useful (0 votes)
7 views14 pages

STACKS

Uploaded by

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

STACKS

Uploaded by

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

Create a stack of integers and push the numbers 1 to 10 onto it.

Then, print all


elements of the stack.

#include<bits/stdc++.h>
int main() {
std::stack<int> stack;

for (int i = 1; i <= 10; ++i) {


stack.push(i);
}
std::cout << "Stack elements:" << std::endl;
while (!stack.empty()) {
std::cout << stack.top() << " ";
stack.pop();
}

return 0;
}

-----------------------------------------------------------------------

Initialize a stack of strings. Push the strings "apple", "banana", and "cherry"
onto it. Pop the top element and print it.

#include<bits/stdc++.h>
int main() {
std::stack<std::string> stack;

stack.push("apple");
stack.push("banana");
stack.push("cherry");
std::cout << "Popped element: " << stack.top() << std::endl;
stack.pop();

return 0;
}

-----------------------------------------------------------------------

Write a program that reads 5 integers from the user, pushes them onto a stack, and
then prints the stack in LIFO (Last In First Out) order.

#include<bits/stdc++.h>
int main() {
std::stack<int> stack;
int num;
std::cout << "Enter 5 integers:" << std::endl;
for (int i = 0; i < 5; ++i) {
std::cin >> num;
stack.push(num);
}
std::cout << "Stack in LIFO order:" << std::endl;
while (!stack.empty()) {
std::cout << stack.top() << " ";
stack.pop();
}

return 0;
}

-------------------------------------------------------------------------

Create a stack of characters. Push the characters 'A', 'B', 'C', and 'D' onto it.
Print the stack, then pop all elements and print them again.

#include<bits/stdc++.h>
int main() {
std::stack<char> stack;
stack.push('A');
stack.push('B');
stack.push('C');
stack.push('D');
std::cout << "Stack elements (LIFO order):" << std::endl;
std::stack<char> tempStack = stack;
while (!tempStack.empty()) {
std::cout << tempStack.top() << " ";
tempStack.pop();
}
std::cout << std::endl;

std::cout << "Popping and printing elements:" << std::endl;


while (!stack.empty()) {
std::cout << stack.top() << " ";
stack.pop();
}

return 0;
}

------------------------------------------------------------------------------

Implement a function that takes a stack of integers and returns the sum of all
elements in the stack without modifying the stack.

#include<bits/stdc++.h>
int sumStack(std::stack<int> stack) {
int sum = 0;
while (!stack.empty()) {
sum += stack.top();
stack.pop();
}

return sum;
}

int main() {
std::stack<int> stack;
stack.push(10);
stack.push(20);
stack.push(30);
stack.push(40);
stack.push(50);

int sum = sumStack(stack);


std::cout << "Sum of stack elements: " << sum << std::endl;
std::cout << "Stack after summing elements (in LIFO order):" << std::endl;
while (!stack.empty()) {
std::cout << stack.top() << " ";
stack.pop();
}

return 0;
}

-----------------------------------------------------------------------------------
----------------

Create a stack of floating-point numbers. Push the numbers 2.5, 3.6, and 4.7 onto
it. Print the top element of the stack without removing it.

#include<bits/stdc++.h>
int main() {
std::stack<float> stack;
stack.push(2.5f);
stack.push(3.6f);
stack.push(4.7f);

std::cout << "Top element of the stack: " << stack.top() << std::endl;

return 0;
}

-----------------------------------------------------------------------------------
---------------------

Write a program to push 10 numbers onto a stack and then pop and print the elements
only if they are even numbers.

#include<bits/stdc++.h>
int main() {
std::stack<int> stack;

for (int i = 1; i <= 10; ++i) {


stack.push(i);
}
std::cout << "Even numbers in the stack:" << std::endl;
while (!stack.empty()) {
int topElement = stack.top();
if (topElement % 2 == 0) {
std::cout << topElement << " ";
}
stack.pop();
return 0;
}

-----------------------------------------------------------------------------------
--------------------------------------

Push the first 5 prime numbers onto a stack. Write a function to check if a number
is present in the stack.

#include<bits/stdc++.h>
bool isNumberInStack(std::stack<int> stack, int number) {
while (!stack.empty()) {
if (stack.top() == number) {
return true;
}
stack.pop();
}
return false;
}

int main() {
std::stack<int> stack;

stack.push(2);
stack.push(3);
stack.push(5);
stack.push(7);
stack.push(11);

int numberToCheck = 5;
if (isNumberInStack(stack, numberToCheck)) {
std::cout << numberToCheck << " is present in the stack." << std::endl;
} else {
std::cout << numberToCheck << " is not present in the stack." << std::endl;
}

return 0;
}

-----------------------------------------------------------------------------------
--------------------------

Create a stack of integers and push 15 random numbers onto it. Implement a function
to clear all elements from the stack.

#include <iostream>
#include <stack>
#include <cstdlib>
#include <ctime>

void clearStack(std::stack<int>& stack) {


while (!stack.empty()) {
stack.pop();
}
}

int main() {
std::stack<int> stack;
std::srand(std::time(0)); for (int i = 0; i < 15; ++i) {
int randomNumber = std::rand() % 100;
stack.push(randomNumber);
}

std::cout << "Stack elements before clearing:" << std::endl;


std::stack<int> tempStack = stack;
while (!tempStack.empty()) {
std::cout << tempStack.top() << " ";
tempStack.pop();
}
std::cout << std::endl;

clearStack(stack);
std::cout << "Stack is " << (stack.empty() ? "empty" : "not empty") << "." <<
std::endl;

return 0;
}

-----------------------------------------------------------------------------------
----------------------------

Initialize a stack of integers and push 5 values onto it. Write a function to print
the stack's size without removing any elements.

#include<bits/stdc++.h>
void printStackSize(const std::stack<int>& stack) {
std::cout << "Stack size: " << stack.size() << std::endl;
}

int main() {
std::stack<int> stack;
stack.push(10);
stack.push(20);
stack.push(30);
stack.push(40);
stack.push(50);
printStackSize(stack);

return 0;
}

-----------------------------------------------------------------------------------
----------------------------

Create a stack of strings. Push the strings "first", "second", "third", and
"fourth". Write a function to print the stack in reverse order.

#include<bits/stdc++.h>
void printStackInReverse(std::stack<std::string> stack) {
std::vector<std::string> temp;
while (!stack.empty()) {
temp.push_back(stack.top());
stack.pop();
}
std::cout << "Stack elements in reverse order:" << std::endl;
for (const std::string& element : temp) {
std::cout << element << " ";
}
std::cout << std::endl;
}

int main() {
std::stack<std::string> stack;
stack.push("first");
stack.push("second");
stack.push("third");
stack.push("fourth");
printStackInReverse(stack);

return 0;
}

---------------------------------------------------------------------------------

Write a program that uses a stack to check if a given string (containing


parentheses) has balanced parentheses.

#include<bits/stdc++.h>
bool areParenthesesBalanced(const std::string& str) {
std::stack<char> stack;
for (char ch : str) {
if (ch == '(' || ch == '{' || ch == '[') {
stack.push(ch);
}
else if (ch == ')' || ch == '}' || ch == ']') {
if (stack.empty()) {
return false;
}

char top = stack.top();


stack.pop();

if ((ch == ')' && top != '(') ||


(ch == '}' && top != '{') ||
(ch == ']' && top != '[')) {
return false;
}
}
}
return stack.empty();
}

int main() {
std::string input;

std::cout << "Enter a string containing parentheses: ";


std::getline(std::cin, input);
if (areParenthesesBalanced(input)) {
std::cout << "The parentheses are balanced." << std::endl;
} else {
std::cout << "The parentheses are not balanced." << std::endl;
}

return 0;
}

-----------------------------------------------------------------------------------
-----------

Implement a stack of integers and push 20 values onto it. Write a function to find
the average of all the numbers in the stack.

#include <iostream>
#include <stack>
double calculateAverage(std::stack<int> stack) {
if (stack.empty()) {
return 0.0;
}

int sum = 0;
int count = 0;
while (!stack.empty()) {
sum += stack.top();
stack.pop();
count++;
}
return static_cast<double>(sum) / count;
}

int main() {
std::stack<int> stack;
for (int i = 1; i <= 20; ++i) {
stack.push(i * 2);
}
double average = calculateAverage(stack);
std::cout << "The average of the stack elements is: " << average << std::endl;

return 0;
}

-----------------------------------------------------------------------------------
-----------------------------------

Push the numbers from 1 to 10 onto a stack. Write a function to remove all odd
numbers from the stack and print the remaining even numbers.

#include <iostream>
#include <stack>
void removeOddNumbersAndPrintEven(std::stack<int>& stack) {
std::stack<int> tempStack;
while (!stack.empty()) {
if (stack.top() % 2 == 0) {
tempStack.push(stack.top());
}
stack.pop();
}
std::cout << "Even numbers in the stack:" << std::endl;
while (!tempStack.empty()) {
std::cout << tempStack.top() << " ";
stack.push(tempStack.top()); // Optional: Restore original stack with even
numbers
tempStack.pop();
}
std::cout << std::endl;
}

int main() {
std::stack<int> stack;
for (int i = 1; i <= 10; ++i) {
stack.push(i);
}
removeOddNumbersAndPrintEven(stack);
return 0;
}

-----------------------------------------------------------------------------------
--------------------

Create a stack of characters. Push the characters of a given string onto the stack.
Write a function to check if the string is a palindrome using the stack

#include<bits/stdc++.h>
using namespace std;

bool isPalindrome(const string &str) {


stack<char> s;
for (char ch : str) {
s.push(ch);
}
for (char ch : str) {
if (ch != s.top()) {
return false;
}
s.pop();
}

return true;
}

int main() {
string input;

cout << "Enter a string: ";


cin >> input;

if (isPalindrome(input)) {
cout << "The string is a palindrome." << endl;
} else {
cout << "The string is not a palindrome." << endl;
}

return 0;
}

-----------------------------------------------------------------------------------
-------

Initialize a stack of integers and push 5 values. Write a function to duplicate the
top element of the stack and push the duplicate onto the stack.

#include<bits/stdc++.h>
using namespace std;

void duplicateTop(stack<int> &s) {


if (!s.empty()) {
int topElement = s.top();
s.push(topElement);
}
else {
cout << "Stack is empty, cannot duplicate top element." << endl;
}
}

int main() {
stack<int> s;
s.push(10);
s.push(20);
s.push(30);
s.push(40);
s.push(50);

cout << "Stack before duplicating the top element:" << endl;
stack<int> temp = s;
while (!temp.empty()) {
cout << temp.top() << endl;
temp.pop();
}

duplicateTop(s);

cout << "\nStack after duplicating the top element:" << endl;
temp = s; // Reset the temporary stack to the updated stack
while (!temp.empty()) {
cout << temp.top() << endl;
temp.pop();
}

return 0;
}

-----------------------------------------------------------------------------------
---------------------

Initialize a stack of integers and push 5 values. Write a function to duplicate the
top element of the stack and push the duplicate onto the stack.

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

void duplicateTop(stack<int> &s) {


if (!s.empty()) {
int topElement = s.top();
s.push(topElement);
} else {
cout << "Stack is empty, cannot duplicate top element." << endl;
}
}

int main() {
stack<int> s;
s.push(10);
s.push(20);
s.push(30);
s.push(40);
s.push(50);
cout << "Stack before duplicating the top element:" << endl;
stack<int> temp = s;
while (!temp.empty()) {
cout << temp.top() << endl;
temp.pop();
}
duplicateTop(s);

cout << "\nStack after duplicating the top element:" << endl;
temp = s; // Reset the temporary stack to the updated stack
while (!temp.empty()) {
cout << temp.top() << endl;
temp.pop();
}

return 0;
}

-----------------------------------------------------------------------------------
-------------------------------------

Initialize a vector with 10 integers. Push all elements onto a stack. Print the top
5 elements without modifying the stack.

#include<bits/stdc++.h>
using namespace std;

void printTopElements(stack<int> s, int n) {


// Print the top 'n' elements without modifying the stack
cout << "Top " << n << " elements:" << endl;
for (int i = 0; i < n && !s.empty(); ++i) {
cout << s.top() << endl;
s.pop();
}
}

int main() {
vector<int> vec = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
stack<int> s;
for (int i = 0; i < vec.size(); ++i) {
s.push(vec[i]);
}
printTopElements(s, 5);

return 0;
}

-----------------------------------------------------------------------------------
----------------------------

Initialize a map with int keys and float values. Push all keys and values into a
stack as pairs. Print all pairs in LIFO order.

#include<bits/stdc++.h>
using namespace std;

void printTopElements(stack<int> s, int n) {


cout << "Top " << n << " elements:" << endl;
for (int i = 0; i < n && !s.empty(); ++i) {
cout << s.top() << endl;
s.pop();
}
}

int main() {
vector<int> vec = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
stack<int> s;
for (int i = 0; i < vec.size(); ++i) {
s.push(vec[i]);
}
printTopElements(s, 5);

return 0;
}

using namespace std;

int main() {
map<int, float> myMap = {
{1, 1.1f},
{2, 2.2f},
{3, 3.3f},
{4, 4.4f},
{5, 5.5f}
};

stack<pair<int, float>> s;
for (const auto& entry : myMap) {
s.push(entry);
}

cout << "Stack contents in LIFO order:" << endl;


while (!s.empty()) {
pair<int, float> topPair = s.top();
cout << "Key: " << topPair.first << ", Value: " << topPair.second << endl;
s.pop();
}

return 0;
}

-----------------------------------------------------------------------------------
------------------------------------------------

Create a map of string keys and int values. Push all values onto a stack, then pop
elements until you find the first even number and print it.

#include<bits/stdc++.h>
using namespace std;

void printTopElements(stack<int> s, int n) {


cout << "Top " << n << " elements:" << endl;
for (int i = 0; i < n && !s.empty(); ++i) {
cout << s.top() << endl;
s.pop();
}
}

int main() {
vector<int> vec = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
stack<int> s;
for (int i = 0; i < vec.size(); ++i) {
s.push(vec[i]);
}
printTopElements(s, 5);

return 0;
}

using namespace std;

int main() {
map<string, int> myMap = {
{"one", 1},
{"two", 2},
{"three", 3},
{"four", 4},
{"five", 5}
};
stack<int> s;
for (const auto& entry : myMap) {
s.push(entry.second);
}
bool foundEven = false;
while (!s.empty()) {
int topValue = s.top();
s.pop();
if (topValue % 2 == 0) {
cout << "First even number found: " << topValue << endl;
foundEven = true;
break;
}
}

if (!foundEven) {
cout << "No even numbers found in the stack." << endl;
}

return 0;
}

-----------------------------------------------------------------------------------
----------------------

Initialize a vector of float values. Push all elements onto a stack. Write a
function to calculate the average of the stack elements and print it.

#include <iostream>
#include <stack>
#include <vector>
using namespace std;

float calculateAverage(stack<float> s) {
if (s.empty()) {
cout << "Stack is empty. Cannot calculate average." << endl;
return 0.0f;
}

float sum = 0.0f;


int count = 0;
while (!s.empty()) {
sum += s.top();
s.pop();
count++;
}

return sum / count;


}

int main() {
vector<float> vec = {1.5f, 2.5f, 3.5f, 4.5f, 5.5f};
stack<float> s;
for (float value : vec) {
s.push(value);
}

float average = calculateAverage(s);


cout << "The average of the stack elements is: " << average << endl;

return 0;
}

-----------------------------------------------------------------------------------
------------------------------------

Given a map with string keys and double values, push all keys onto a stack and then
pop and print each key, appending a count of how many times each key appears in the
map.

#include <bits/stdc++.h>
#include <map>
#include <unordered_map>
using namespace std;

void printKeysWithCount(stack<string> s, const map<string, double> &myMap) {


unordered_map<string, int> keyCount;
for (const auto &entry : myMap) {
keyCount[entry.first]++;
}

while (!s.empty()) {
string key = s.top();
s.pop();
cout << "Key: " << key << ", Count: " << keyCount[key] << endl;
}
}

int main() {
map<string, double> myMap = {
{"apple", 1.1},
{"banana", 2.2},
{"apple", 3.3},
{"orange", 4.4},
{"banana", 5.5}
};
stack<string> s;
for (const auto &entry : myMap) {
s.push(entry.first);
}
printKeysWithCount(s, myMap);

return 0;
}

-----------------------------------------------------------------------------------
----------

You might also like