C examples for Data Structure:Stack
Reverse Data with Stack
#include <stdio.h> #include <stdlib.h> #define Error -9999//from w w w. ja v a2 s.co m typedef struct { char ch; } StackData; typedef struct node { int num; struct node *next; } Node, *NodePtr; typedef struct stackType { NodePtr top; } StackType, *Stack; Stack initStack() { Stack sp = (Stack)malloc(sizeof(StackType)); sp->top = NULL; return sp; } int empty(Stack S) { return (S->top == NULL); } void push(Stack S, int n) { NodePtr np = (NodePtr)malloc(sizeof(Node)); np->num = n; np->next = S->top; S->top = np; } int pop(Stack S) { if (empty(S)) return Error; int hold = S->top->num; NodePtr temp = S->top; S->top = S->top->next; free(temp); return hold; } int main() { StackData temp; char c; Stack S = initStack(); printf("Type some data and press Enter\n"); while ((c = getchar()) != '\n') { temp.ch = c; push(S, temp.ch); } printf("\nData in reverse order\n"); while (!empty(S)) putchar(pop(S)); putchar('\n'); }