Sunday, April 5, 2015

[Data Structures - C] Stack data structure

It is basic data structure.(Basic data structure is linked list, stack, queue)
If you want to learn about stack. Please watch carefully function pop and push.



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


typedef struct Node {
 struct Node *next;
 char *data;
} Node;

Node *top;

bool push(Node **, char *);
bool pop(Node **, char **);
void printStack(Node *);

int main() {
 int command = 0;
 char input = NULL;

 top = NULL;
 while (true) {
  printf("Stack program. Please enter command\n");
  printf("1. Push data\n");
  printf("2. Pop data\n");
  printf("3. Print stack data\n");
  printf("4. Exit program\n");
  printf("Enter your command : ");
  scanf("%d", &command);
  getchar();
  switch (command) {
   case 1:
    printf("Please enter character what you wnat to push : ");
    scanf("%c", &input);
    getchar();
    
    if (push(&top, input)) {
     printf("Push complete.\n");
    }
    else {
     printf("Push fail.\n");
    }
    
    break;
   case 2:
    if (pop(&top, &input)) {
     printf("The data what poped is %c \n", input);
    }
    else {
     printf("There is no element. Please push anything.\n");
    }
    break;
   case 3:
    printStack(top);
    break;
   case 4:
    printf("Exit program. Bye Bye\n");
    exit(0);
   default:
    printf("There is no command like you entered. Please try again. \n");
  }
 }
 return 0;
}

bool push(Node **top, char *data) {
 Node *tempNode = (Node *)malloc(sizeof(Node));
 if (!tempNode) return false;
 
 tempNode->data = data;
 tempNode->next = *top;
 *top = tempNode;

 return true;
}

bool pop(Node **top, char **data){
 Node *tempNode = *top;
 if (!tempNode) return false;

 *data = tempNode->data;
 *top = tempNode->next;
 free(tempNode);

 return true;
}

void printStack(Node *top) {
 Node *currentNode = top;
 while (currentNode!=NULL) {
  printf("Data - %c \n", currentNode->data);
  currentNode = currentNode->next;
 }
}





No comments:

Post a Comment