Creating a stack using linked list in C++. Create a Stack Class using a linked l
ID: 3679327 • Letter: C
Question
Creating a stack using linked list in C++.
Create a Stack Class using a linked list. The only functions are Push() and Pop(). The push function APPENDS to the end of the linked list and the POP function deletes the last entry from the stack. You need to display the last entry prior to deleting it from the stack.
When I call the function<pop>. It doesn't pop the last element
eg: input: 10, 20, 30
output: 20, 10
Anybody know how to fix it? thanks
#include<cstdlib>
#include<iostream>
using namespace std;
struct Node
{
int data;
Node *link;
};
typedef Node *NodePtr;
class Stack
{
public:
Stack();
void push(int value);
int pop();
void print() const;
NodePtr top;
};
Stack::Stack()
{
top= NULL;
}
void Stack::push (int value)
{
NodePtr temp_ptr;
temp_ptr = new Node;
temp_ptr->data = value;
temp_ptr->link = top;
top = temp_ptr;
}
int Stack :: pop()
{
if (top == NULL)
{
cout<< "Error: Popping an empty stack. " << endl;
exit(1);
}
int result = top->data;
NodePtr temp_ptr;
temp_ptr= top;
top= top-> link;
delete temp_ptr;
return result;
}
void Stack:: print() const
{
Node* temp = top;
while (temp != NULL)
{
cout << temp-> data << ",";
temp = temp->link;
}
}
int main()
{
Stack s;
int nOfElements;
int value;
int count= 0;
cout<< "How many elements do you want to push into the stack?"<< endl;
cin>> nOfElements;
while(count < nOfElements)
{
cout << "Enter the value to be put into the stack: "<< endl;
cin>> value;
s.push(value);
count++;
}
cout<<"Popping the values" << endl;
s.pop();
s.print();
return 0;
}
Explanation / Answer
#include <stdio.h>
#include <stdlib.h>
struct Node
{
int Data;
struct Node *next;
}*top;
void popStack()
{
struct Node *temp, *var=top;
if(var==top)
{
top = top->next;
free(var);
}
else
printf(" Stack Empty");
}
void push(int value)
{
struct Node *temp;
temp=(struct Node *)malloc(sizeof(struct Node));
temp->Data=value;
if (top == NULL)
{
top=temp;
top->next=NULL;
}
else
{
temp->next=top;
top=temp;
}
}
void display()
{
struct Node *var=top;
if(var!=NULL)
{
printf(" Elements are as: ");
while(var!=NULL)
{
printf(" %d ",var->Data);
var=var->next;
}
printf(" ");
}
else
printf(" Stack is Empty");
}
int main(int argc, char *argv[])
{
int i=0;
top=NULL;
printf(" 1. Push to stack");
printf(" 2. Pop from Stack");
printf(" 3. Display data of Stack");
printf(" 4. Exit ");
while(1)
{
printf(" Choose Option: ");
scanf("%d",&i);
switch(i)
{
case 1:
{
int value;
printf(" Enter a values to push into Stack: ");
scanf("%d",&value);
push(value);
display();
break;
}
case 2:
{
popStack();
display();
break;
}
case 3:
{
display();
break;
}
case 4:exit(1);
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.