Tuesday, December 27, 2011

Stack Using List List 2

接續上一篇Stack Using List List,我在程式碼上加入多點comments和一些修改,修改部份如下:

  • pop所移除掉的值以函式回傳值的方式呈現
  • 使用free()函式釋放掉不需要的記憶體空間(pop時)

#include 
#include 

#define PUSH 1
#define POP  2
#define DISPLAY 3

/*
 * Structure node declaration
 */
struct node{
 int data;
 struct node *next;
};

struct node *top = NULL;

/*
 * Functions declarations
 */
static void push(int num);
static int pop();
static void display();

int main(void){

 while(1){

  // let user select which operation to do on the stack
  int sel;
  printf("[Stack]\t(1)push\t(2)pop\t(3)display >> ");
  if(scanf("%d",&sel)==EOF) break;

  // do the operation depends on the selection from the user
  int temp;
  switch(sel){

   // push
   case PUSH:
    // scan in a integer
    printf("push >> ");
    scanf("%d", &temp);
    // push it into the stack
    push(temp);
    break;

   // pop
   case POP:
    printf("pop >> %d\n", pop());
    break;

   // display all the items in the stack
   case DISPLAY:
    display();
    break;

   // wrong selections handler
   default:
    printf("Wrong Selection.\n");

  }

 }


 //end
 printf("Exit Program.\n");

 return 0;
}

/*
 * Function : push
 */
static void push(int num){

 // declare a new node pointer
 struct node *temp;

 // let temp point to a new node which store the new data
 temp = (struct node *)malloc(sizeof(struct node));
 temp->data = num;

 // let temp link to next
 temp->next = top;

 // let temp become top
 top = temp;

}

/*
 * Function : pop
 */
static int pop(){

 // declare a int variable to store the pop out data
 int popData = -1;

 // if there's something in the stack
 if(top!=NULL){

  // declare dump as a pointer, which points
  // to the node going to be deleted
  struct node *dump;
  dump = top;

  // store the data and return it at the end of function
  popData = top->data;

  // let top point to the next node
  top = top->next;

  // free/release the memory which stores the deleted node
  free(dump);
 }
 // if the stack is empty
 else{
  printf("Stack Bottom.\n");
 }

 return popData;
}

/*
 * Function : display
 * Display all the elements in the stack.
 */
static void display(){

 // deleclare ptr as same as top
 struct node *ptr = top;

 // scan through the link list until ptr==NULL
 while(ptr){

  // print out the data
  printf("%d\n", ptr->data);

  // ptr points to the next node
  ptr = ptr->next;

 }

}

//end

No comments:

Post a Comment