Linked List Implementation of Stack
Linked List Implementation of Stack
Instead of using array, we can also use linked list to implement stack. Linked list
allocates the memory dynamically. However, time complexity in both the scenario
is same for all the operations i.e. push, pop and peek.
The top most node in the stack always contains null in its address field. Lets
discuss the way in which, each operation is performed in linked list
implementation of stack.
void push ()
int val;
if(ptr == NULL)
else
{
scanf("%d",&val);
if(head==NULL)
ptr->val = val;
head=ptr;
else
ptr->val = val;
ptr->next = head;
head=ptr;
printf("Item pushed");
}
Deleting a node from the stack (POP operation)
void pop()
{
int item;
struct node *ptr;
if (head == NULL)
{
printf("Underflow");
}
else
{
item = head->val;
ptr = head;
head = head->next;
free(ptr);
printf("Item popped");
}
}
Display the nodes (Traversing)
Displaying all the nodes of a stack needs traversing all the nodes of the
linked list organized in the form of stack. For this purpose, we need to
follow the following steps.
void display()
{
int i;
struct node *ptr;
ptr=head;
if(ptr == NULL)
{
printf("Stack is empty\n");
}
else
{
printf("Printing Stack elements \n");
while(ptr!=NULL)
{
printf("%d\n",ptr->val);
ptr = ptr->next;
}
}
}