Stack implemented with SLL Design and code your own LIFO Stack using single like
ID: 3807070 • Letter: S
Question
Stack implemented with SLL
Design and code your own LIFO Stack using single liked list to hold a list of integers. Use the C++ “struct” structure to create your SLL nodes. Node position numbering should start with one.
Your program should include the main program to test and demonstrate one function for each Stack operations including:
InitStack – Initialize LIFO Stack
PushStack – Add an item to top of Stack at
PrintStack – Print out the Stack items
PopStack – Remove and return top item from Stack
TopStack – Returns the first item on Stack without deleting it
EmptyStack – Checks for empty Stack condition (TRUE/FALLS)
ClearStack – Delete all items from Stack
Explanation / Answer
PROGRAM CODE:
#include <iostream>
using namespace std;
int size;
struct Node
{
int position;
int data;
Node *next;
}*front;
void InitStack()
{
front = NULL;
size = 0;
}
void PushStack(int item)
{
struct Node *node = new Node;
size++;
node->data = item;
node->next = NULL;
node->position = size;
if(front == NULL)
front = node;
else
front->next = node;
}
void PrintStack()
{
struct Node *temp = front;
cout<<"Stack: [ ";
while(temp!= NULL)
{
cout<<temp->data<<" ";
temp = temp->next;
}
cout<<"] ";
}
int PopStack()
{
if(size>1)
{
struct Node *temp = front;
int item;
while(temp->next != NULL && temp->next->position != size)
temp = temp->next;
item = temp->next->data;
temp->next = NULL;
size--;
return item;
}
else if(size == 1)
{
int item = front->data;
size--;
front = NULL;
return item;
}else return NULL;
}
int TopStack()
{
if(size>1)
{
struct Node *temp = front;
int item;
while(temp->next != NULL && temp->next->position != size)
temp = temp->next;
item = temp->next->data;
return item;
}
else if(size == 1)
{
int item = front->data;
return item;
}else return NULL;
}
bool EmptyStack()
{
return size==0;
}
void ClearStack()
{
front = NULL;
size = 0;
}
int main() {
InitStack();
PushStack(2);
PushStack(4);
PrintStack();
cout<<"Removed Element: "<<PopStack()<<endl;
cout<<"Removed Element: "<<PopStack()<<endl;
cout<<"Is Stack empty? ";
if(EmptyStack())
cout<<" Yes"<<endl;
else cout<<" No"<<endl;
PushStack(6);
PushStack(8);
PrintStack();
cout<<"Top Element: "<<TopStack()<<endl;
ClearStack();
cout<<"Is Stack empty? ";
if(EmptyStack())
cout<<" Yes"<<endl;
else cout<<" No"<<endl;
return 0;
}
OUTPUT:
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.