/********************************************
 * Author Name: Piyawut Tantimekabut (Toon) *
 *                         *
 * Date: February 13, 2001                  *
 * Program Name: Stack-220                  *
 *******************************************/

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

/* node structure for linked list*/
/* element is kept in value*/
/* min up to current element is kept in min */
struct node {
  int value;
  int min;
  struct node *next;
};

/* header node for the list */
struct node *header = NULL;

void findMin() {
  struct node *current;

  /* check emptiness of the stack */
  current = header;
  if (header == NULL) {
    printf("Error!!! Stack is empty.\n\n");
    return;
  }

  /* print minimum for non-empty stack */
  printf("The minimum is %d.\n", current->min);
}

void pushStack() {

  int num;

  struct node *current, *newNode;

  /* allocate new memory for new element */
  newNode = malloc(sizeof(struct node));

  current = header;

  /* ask for input of number to be pushed */
  printf("Please enter the number to be pushed: ");
  scanf("%d",&num);

  /* put value into node */
  newNode->value = num;

  /* determine min value and link the node into the list */
  if (current == NULL) {
    header = newNode;
    newNode->min = num;
  }
  else if (current->min < num) {
    newNode->min= current->min;
    newNode->next = current;
    header = newNode;
  }
  else {
    newNode->min=num;
    newNode->next = current;
    header = newNode;
  }
}

void popStack() {
  struct node *oldNode;

  oldNode = header;

  /* check emptiness of the stack */
  if (header == NULL) {
    printf("Error!!! Stack already empty.\n\n");
    return;
  }

  /* print element to be popped */
  printf("Popping stack containing element: %d.\n", oldNode->value);
  
  /*popping stack and clearing memory */
  header = oldNode->next;
  free(oldNode);
}

void main() {
  
  int input;
 
  /* menu for the program */
  while (input == input) {
    printf("Welcome to SpecialStack220 by Piyawut Tantimekabut\n");
    printf("1. Push an element into the stack\n");
    printf("2. Pop an element out of the stack\n");
    printf("3. Find minimum value in a stack\n");
    printf("4. Quit\n");
    printf("Please make a selection:");
    
    scanf("%d",&input);
    
    switch (input) {
      case 1:  pushStack();
               break;
      case 2:  popStack();
               break;
      case 3:  findMin();
               break;
      case 4:  return;
      default: printf("Error!!! Invalid input\n");
    }

  }
}







