0% found this document useful (0 votes)
14 views2 pages

Stack

Uploaded by

pquan7937
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)
14 views2 pages

Stack

Uploaded by

pquan7937
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/ 2

#include <bits/stdc++.

h>
using namespace std;

struct node {
int data;
struct node *next;
};

typedef struct node node;

// Create a new node


node *makeNode(int x) {
node *newNode = new node();
newNode->data = x;
newNode->next = nullptr;
return newNode;
}

// Add to the top of the stack


void push(node **top, int x) {
node *newNode = makeNode(x);
newNode->next = *top;
*top = newNode;
}

// Remove the top of the stack


void pop(node **top) {
if (*top != nullptr) {
node *tmp = *top;
*top = tmp->next;
delete tmp;
} else {
cout << "Stack is empty!\n";
}
}

// Return the top element's data


int Top(const node *top) { // 'top' is now a pointer to const
if (top != nullptr) {
return top->data;
}
cout << "Stack is empty!\n";
return -1; // or another indicator for an empty stack
}

// Count the number of elements in the stack


int size(const node *top) { // 'top' is now a pointer to const
int ans = 0;
while (top != nullptr) {
++ans;
top = top->next;
}
return ans;
}

You might also like