0% found this document useful (0 votes)
18 views4 pages

Program 19

C plus plus program

Uploaded by

dubeyvipin715
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)
18 views4 pages

Program 19

C plus plus program

Uploaded by

dubeyvipin715
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/ 4

#include <iostream>

// Node structure for the linked list

struct Node {

int data;

Node* next;

// Constructor to initialize the node

Node(int value) : data(value), next(nullptr) {}

};

// Stack class

class Stack {

private:

Node* top; // Pointer to the top of the stack

public:

// Constructor to initialize an empty stack

Stack() : top(nullptr) {}

// Destructor to clean up the stack

~Stack() {

while (!isEmpty()) {

pop();

// Push a new element onto the stack

void push(int value) {

Node* newNode = new Node(value);

newNode->next = top;
top = newNode;

// Pop the top element off the stack

void pop() {

if (isEmpty()) {

std::cerr << "Stack is empty. Cannot pop." << std::endl;

return;

Node* temp = top;

top = top->next;

delete temp;

// Peek at the top element of the stack

int peek() const {

if (isEmpty()) {

std::cerr << "Stack is empty. Cannot peek." << std::endl;

return -1; // Indicate error with a special value

return top->data;

// Check if the stack is empty

bool isEmpty() const {

return top == nullptr;

// Display the contents of the stack

void display() const {

Node* current = top;


std::cout << "Stack (top to bottom): ";

while (current != nullptr) {

std::cout << current->data << " ";

current = current->next;

std::cout << std::endl;

};

int main() {

Stack stack;

stack.push(10);

stack.push(20);

stack.push(30);

std::cout << "Stack after pushes:" << std::endl;

stack.display();

std::cout << "Top element: " << stack.peek() << std::endl;

stack.pop();

std::cout << "Stack after one pop:" << std::endl;

stack.display();

return 0;

}
Output

Stack after pushes:

Stack (top to bottom): 30 20 10

Top element: 30

Stack after one pop:

Stack (top to bottom): 20 10

You might also like