Stack Implementation Using Linked-List

The stack implementation using the linked list.

Advantages:

  1. Always takes constant time to push and pop the elements
  2. Can grow to infinite size
Disadvantages:
  1. More time take to find the k th element in the list
  2. Require more memory storage for each data element

Implementation of Stack using the Linked List

  1. First step is to define the node structure
  2. Variable name called TOP for indexing 
  3. Check the condition for Empty and Full of the list
  4. Make a function to display the List elements
  5. Make a function for PUSH and POP operation
#include
#include

struct node
{
int data;
struct node *next;
}*top=NULL;

void push()
{
int n;
struct node *newNode;
newNode=(struct node*)malloc(sizeof(struct node));
printf("enter the data\n");
scanf("%d",&n);
newNode->data=n;
if (top==NULL)
newNode->next=NULL;
else
newNode->next=top;
top=newNode;
printf("insert is sucessfull");
}

void pop()
{
if (top==NULL)
printf("stack is empty");
else
{
struct node* temp=top;
printf("deleted the element:%d\n",temp->data);
top=temp->next;
free(temp);
}
}

void display()
{
if(top==NULL)
printf("stack is empty\n");
else
{
struct node *temp;
temp=top;
while(temp->next!=NULL)
{
printf("stack elements%d------->\n",temp->data);
temp=temp->next;
}
printf("stack elements%d------->\n",temp->data);
}
}

int main()
{
int choice,n;
while(1)
{
printf("1:push into the stack\n");
printf("2:pop into the stack\n");
printf("3:display the stack elements\n");
printf("4:exit\n");
printf("-------------------");
printf("enter your choice");
scanf("%d",&choice);
switch(choice)
{
case 1:
   push();
   break;
case 2:
   pop();
   break;
case 3:
  display();
  break;
case 4:
  exit(0);
  break;
default :
  printf("invlaid choice");
}
}
}


This code you can find at the below link

Comments

Popular posts from this blog

Types of Algorithm and Its Complexity Analysis

First Step of Problem Solving Using Data Structure and Algorithm

Asymptotic Notations