C Program For Implementing a Stack Using a Linked List

/*Implementing a Stack Using a Linked List*/
/* To read some numbers and print them in reverse order. For example, say we have these numbers:
36 15 52 23
And say we want to print the following:
23 52 15 36 */
#include <stdio.h>
#include <stdlib.h>
#define RogueValue -9999
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);
} //end empty

void push(Stack S, int n) {
      NodePtr np = (NodePtr) malloc(sizeof(Node));
      np -> num = n;
      np -> next = S -> top;
      S -> top = np;
} //end push

int pop(Stack S) {
      if (empty(S)) return RogueValue;
      int hold = S -> top -> num;
      NodePtr temp = S -> top;
      S -> top = S -> top -> next;
      return hold;
} //end pop

int main() {
      int n;
      Stack S = initStack();
      printf("Enter some integers, ending with 0\n");
      scanf("%d", &n);
      while (n != 0) {
            push(S, n);
            scanf("%d", &n);
      printf("\nNumbers in reverse order\n");
      while (!empty(S))
            printf("%d ", pop(S));
Bhanu Namikaze

Bhanu Namikaze is an Ethical Hacker, Web Developer, Student and Mechanical Engineer. He Enjoys writing articles, Blogging, Solving Errors and Social Networking. Feel Free to let me know any of your concerns about hacking or let me know if you need any more methods on hacking anything. Enjoy Learning

No comments:

Post a Comment