Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implementing Stack Using Linked List inC++ #325

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
78 changes: 78 additions & 0 deletions Structures/Stack using Linked List
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
// C++ program for linked list implementation of stack
#include <bits/stdc++.h>
using namespace std;

// A structure to represent a stack
class StackNode {
public:
int data;
StackNode* next;
};

StackNode* newNode(int data)
{
StackNode* stackNode = new StackNode();
stackNode->data = data;
stackNode->next = NULL;
return stackNode;
}

int isEmpty(StackNode* root)
{
return !root;
}

void push(StackNode** root, int data)
{
StackNode* stackNode = newNode(data);
stackNode->next = *root;
*root = stackNode;
cout << data << " pushed to stack\n";
}

int pop(StackNode** root)
{
if (isEmpty(*root))
return INT_MIN;
StackNode* temp = *root;
*root = (*root)->next;
int popped = temp->data;
free(temp);

return popped;
}

int peek(StackNode* root)
{
if (isEmpty(root))
return INT_MIN;
return root->data;
}

// Driver code
int main()
{
StackNode* root = NULL;

push(&root, 10);
push(&root, 20);
push(&root, 30);

cout << pop(&root) << " popped from stack\n";

cout << "Top element is " << peek(root) << endl;

cout<<"Elements present in stack : ";
//print all elements in stack :
while(!isEmpty(root))
{
// print top element in stack
cout<<peek(root)<<" ";
// remove top element in stack
pop(&root);
}

return 0;
}

// This is code is contributed by rathbhupendra