Created
March 30, 2013 18:52
-
-
Save kunalkushwaha/5277917 to your computer and use it in GitHub Desktop.
Stack implementation with link list. push, pop and dump_stack function implementation.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <malloc.h> | |
#define SUCCESS 0 | |
#define INVAILD_PTR -1 | |
#define NO_MEM -2 | |
#define INIT_NODE(node) node->next = node->prev = NULL | |
struct node_type | |
{ | |
int data; | |
struct node_type *next; | |
struct node_type *prev; | |
}; | |
struct node_type* new_node(int data) | |
{ | |
struct node_type *temp = (struct node_type*)malloc(sizeof(struct node_type)); | |
if(!temp) | |
{ | |
return NULL; | |
} | |
INIT_NODE(temp); | |
temp->data = data; | |
return temp; | |
} | |
int push(struct node_type *node, struct node_type **top) | |
{ | |
if(!node) | |
{ | |
return INVAILD_PTR; | |
} | |
//push the node on top of stack. | |
if(!*top) | |
{ | |
printf("1st Node on Stack \n"); | |
node->next = NULL; | |
*top = node; | |
} | |
else | |
{ | |
printf("New Node on Stack \n"); | |
node->next = *top; | |
*top = node; | |
} | |
return SUCCESS; | |
} | |
struct node_type * pop(struct node_type **top) | |
{ | |
struct node_type *temp=NULL; | |
if(!*top) | |
{ | |
printf(" Stack Underun!!! \n"); | |
return NULL;//INVAILD_PTR; | |
} | |
temp = *top; | |
*top = (*top)->next; | |
return temp; | |
} | |
int dump_stack(struct node_type *top) | |
{ | |
struct node_type *t_top = top; | |
if(!top) | |
{ | |
return INVAILD_PTR; | |
} | |
do | |
{ | |
printf(" %d -> %s",t_top->data, (!t_top->next)?"NULL":" "); | |
t_top = t_top->next; | |
}while(t_top); | |
} | |
void main() | |
{ | |
struct node_type *temp,*top = NULL; | |
// Input some element in stack. | |
push(new_node(2),&top); | |
push(new_node(3),&top); | |
dump_stack(top); | |
temp = NULL; | |
temp = pop(&top); | |
printf("\npop data %d \n",temp->data); | |
if(temp) | |
free(temp); | |
temp = NULL; | |
temp = pop(&top); | |
printf("pop data %d \n",temp->data); | |
if(temp) | |
free(temp); | |
temp = NULL; | |
temp = pop(&top); | |
if(temp) | |
{ | |
printf("pop data %d \n",temp->data); | |
free(temp); | |
} | |
printf("\n"); | |
return; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment