Thursday, February 5, 2015

Implement stack Using Singly Linked List.

// I am going to implement stack using linked list.
// as I am using linked list , there is not required to check the overflow condition in push operation , becaues I I can grow the stack to the size of my RAM , there is no limitation.

// the cons is that , it requires extra memory to store the link field of the linked list.

#include<stdio.h>
#include<stdlib.h>

struct node
{
int data;
struct node *link;
};

struct node *createNode(struct node *head,int data)  // will create a node and return the pointer to that new node.
{
struct node *p=NULL;

p=(struct node*)malloc(sizeof(struct node));
p->data=data;
p->link=NULL;

return p;
}

// In below function I am passing the pointer to pointer to the structure , because in the defination of the push() operation it do not return any thing , and while puch I have to change the head pointer to the new node , so to reflect the change in main() , I am passing pointer to pointer to structure.

// In linked list implementation of stack , always remember that we have to we have to insert the element to the start of the list and delete the eleemnt from the start of the list , otherwise while deletion , for each deletion we have to traverse the entire list.

void push(struct node **ptrToHead,int data)
{
struct node *head,*p=NULL;
head=*ptrToHead;

p=createNode(head,data);
p->link=head;
head=p;


*ptrToHead=head;
}


int isUnderflow(struct node **ptrToHead)
{
struct node *head=NULL;
head=*ptrToHead;

if(head==NULL)
{
return 1;
}
else
{
return 0;
}
}

// pop() will return the data value it just delete.

int pop(struct node **ptrToHead)
{
struct node *head,*temp=NULL;
int data;

head=*ptrToHead;

if(isUnderflow(ptrToHead))
{
return 0;
}
else
{
temp=head;
head=head->link;
data=temp->data;
free(temp);
temp=NULL;
*ptrToHead=head;
return data;
}


}

void printStack(struct node *head)
{
struct node *temp=head;

if(temp==NULL)
printf("no element to print in the list\n");
else
{
while(1)
{
printf("-%d-",(temp->data));
temp=temp->link;
if(temp==NULL)
{
break;
}
}

printf("\n");

}
}

int main(void)
{
struct node *head=NULL;
int data;

push(&head,5);
push(&head,4);
push(&head,3);
push(&head,2);
push(&head,1);

printStack(head);

return 0;
}

No comments:

Post a Comment