forked from fnplus/interview-techdev-guide
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
[Tushar Gupta]
committed
Oct 7, 2019
1 parent
f722f13
commit 8c5d8eb
Showing
1 changed file
with
62 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,62 @@ | ||
#include <iostream> | ||
using namespace std; | ||
|
||
// class to represent a stack node | ||
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 new_data){ | ||
StackNode* stackNode = newNode(new_data); | ||
stackNode->next = *root; | ||
*root = stackNode; | ||
cout<<new_data<<endl; | ||
} | ||
|
||
int pop(StackNode** root){ | ||
if (isEmpty(*root)) | ||
return -1; | ||
StackNode* temp = *root; | ||
*root = (*root)->next; | ||
int popped = temp->data; | ||
free(temp); | ||
|
||
return popped; | ||
} | ||
int peek(StackNode* root) | ||
{ | ||
if (isEmpty(root)) | ||
return -1; | ||
return root->data; | ||
} | ||
|
||
int main() | ||
{ | ||
StackNode* root = NULL; | ||
cout<<"Stack Push:"<<endl; | ||
push(&root, 100); | ||
push(&root, 200); | ||
push(&root, 300); | ||
cout<<"\nTop element is "<<peek(root)<<endl; | ||
cout<<"\nStack Pop:"<<endl; | ||
while(!isEmpty(root)){ | ||
cout<<pop(&root)<<endl; | ||
} | ||
|
||
cout<<"Top element is "<<peek(root)<<endl; | ||
|
||
return 0; | ||
} |