1: #include <stdio.h>2: #include <malloc.h>
3: #include <ctype.h>4:5: //stack implementation using link list
6: typedef struct node7: {8: int data;
9: struct node *next;
11: }stackNode;12:13: stackNode *head = NULL;14: int size = 0;
15:16: int push(stackNode **head, int data)17: {18: stackNode *newNode = (stackNode*)malloc(sizeof(stackNode));19: if(newNode == NULL)
20: return 0;
21:22: newNode->data = data;23: newNode->next = NULL;24:25: if(*head == NULL)
26: {27: *head = newNode;28: size++;29: return 1;
30: }31: else
32: {33: newNode->next = *head;34: *head = newNode;35: size++;36: return 1;
37: }38: }39:40: stackNode* pop(stackNode **head)41: {42: stackNode *topNode = NULL;43:44: if(*head == NULL)
45: return NULL;
46:47: //top node is returned
48: topNode = (stackNode*)malloc(sizeof(stackNode));49: if(topNode == NULL)
50: return NULL;
51:52: topNode->data = (*head)->data;53: topNode->next = NULL;54:55: stackNode *tempNode = *head;57: *head = (*head)->next;58:59: free(tempNode);
60: tempNode = NULL;62: size--;63:64: return topNode;
65: }66:67: int main(int argc, char **argv)68: {69: int i = 0;
70: stackNode* top;71: int topData = 0;
72: for(;i < 2 ; i++)
73: push(&head,i);74:75: printf("size of stack is %d \n", size);77: do
78: {79: top = pop(&head);80: if(top)
81: {82: printf("poping the top %d \n",top->data);83: free(top);
84: top = NULL;85: }86: else
87: {88: printf("stack empty \n");89: }90: }while(size);
91:92: printf("size of stack is %d \n", size);94: getchar();
96: return 0;
97: }98:
Friday, June 4, 2010
Stack using link list in C
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment