Thursday, 1 November 2012

Application of stacks using single linked lists


                  The main applications of singly linked lists are the implementation of stacks and queues using singly linked lists.With this technique we can dynamically allocate the memory space to the newly inserted one dynamically delete the space allotted to it when deleted.In this article we shall know about how to implement stack and queues.

                  In stacks we need to remember the address of the previous node,so in this case during the declaration of the node we shall divide the node between data field and previous field.The creation of the stack node is as follows:

struct node
{
    
        int data;

       struct node *prev;   (self)
}*temp,*top=NULL;

During the declaration of the variable top it is initialized to null.The main operations we do on stack are push, pop, display.

PUSH OPERATION:

Whenever a push function is made we need to increment the top variable, and while implementing the stack using linked lists we need to remember the address of the previous variable. For this purpose during the declaration of the node for the data field to remember the address of next variable is named as previous. The push function is as follows:

Void push()
{

    temp=(struct node *)malloc(sizeof(struct node));
     printf(“Enter the data in to the data field:”);
     scanf(“%d”,&temp->data);
     temp->prev=NULL;
If(top=NULL)
{
    top=temp;
}
else
{
     temp->prev=top;
    top=temp;
 }
}

POP OPERATION:

                                  Whenever we implement a pop function using linked lists we need to move the top to the before one. The pop function of stacks is done by

Void pop()
{
     if(top=NULL)
       {
               Printf(“stack is empty”);
         }
else
{
                temp=top;
                top=top->prev;
                printf(“element has been poped”);
}
}

DSIPLAY OPERATION:
                                              In stacks we need to display the data in an order such that first in last out,so we need to print the data in reverse order starting with the data which is present at top. The stack display function is

void display()
{

            temp=top;
   if(temp=NULL)
{

      printf(“stack is empty”);
}
else
{
      printf(“%d     “,temp->data);
      temp=temp->data;
}


With this function codes we can implement the stacks by linked lists and reduce the space complexity.



No comments:

Post a Comment