数据结构-堆栈-链表实现

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/cyzyfs/article/details/78158240
/*
 * 堆栈 链表实现
 *
 * */

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

//定义结构
typedef struct _Stack * Stack;
struct _Stack{
    int data;
    Stack next;
};

//创建一个堆栈
Stack CreakStack(){
    Stack stack=(Stack)malloc(sizeof(struct _Stack));
    stack->next=NULL;
    return stack;
}
//判断是否为空
bool isEmpty(Stack stack){
    return (stack->next==NULL);
}
//压栈
bool Push(Stack stack,int num){
    Stack stack1=(Stack)malloc(sizeof(struct _Stack));
    stack1->data=num;
    stack1->next=stack->next;
    stack->next=stack1;
    return true;
}
//出栈
int Pop(Stack stack){
    if(isEmpty(stack)){
        printf("堆栈空");
        return NULL;
    }
    else{
        Stack stack1;
        int numS;
        stack1=stack->next;
        numS=stack1->data;
        stack->next=stack1->next;
        free(stack1);
        return numS;
    }
}

//测试
int main(){
    Stack stack=CreakStack();
    Pop(stack);
    for (int i = 0; i < 10; i++) {
        Push(stack,i);
    }
    Push(stack,10);
    for(int i=0;i<10;i++){
        printf("%d  ",Pop(stack));
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/cyzyfs/article/details/78158240