C實現棧

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

typedef struct stack{
 struct stack* next;
 void* data;
}stack;

    

int stack_create(stack **pStack)
{
 *pStack = NULL;
 return 1;
}

int stack_push(stack** pStack, void* data)
{
 stack* stack_tmp;
 stack_tmp = (stack*) malloc(sizeof(stack));
 if (!stack_tmp)
 {
  return 0;   
 }
 stack_tmp->data = data;
 stack_tmp->next = *pStack;
 *pStack = stack_tmp;
 return 1;
}

int stack_pop(stack** pStack, void** data)
{
 stack* stack_tmp;
 if (!(stack_tmp = *pStack))
 {
  return 0;
 }
 *data = stack_tmp->data;
 *pStack = stack_tmp->next;
 free(stack_tmp);
 return 1;
}

int stack_del(stack** pStack)
{
 stack* next;
 while (*pStack)
 {
  next = (*pStack)->next;
  free(*pStack);
  *pStack = next;
 }
 return 1;
}

 

void main(){
stack* tmp;
CreateStack(&tmp);
int data;
void* tempdata;

for(int i=0; i<3; i++){
   printf("input a number: ");
   scanf("%d",&data);
   stack_push(&score, (void*)data);
}

for(int j=0; j<3; j++){
   stack_pop(&score, &tempdata);
   int d = (int)(int *)tempdata;
   printf("%d ", d);
}

stack_del(&tmp);
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章