C语言 Stack功能实现(自存)

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

typedef int E;

typedef struct node {
    E data;
    struct node* next;
} Node;

typedef struct {
    Node* top;
    int size;
} Stack;

// API
Stack* stack_create(void);
void stack_destroy(Stack* s);

void stack_push(Stack* s, E val);
E stack_pop(Stack* s);
E stack_peek(Stack* s);

bool stack_empty(Stack* s);

int main() {
    Stack *s = stack_create();
    //stack_pop(s);
    stack_push(s, 1);
    stack_push(s, 2);
    stack_push(s, 3);
    int n=stack_empty(s);
    return 0;
}
Stack* stack_create(void) {
    Stack* s = malloc(sizeof(Stack));
    if (!s) {
        printf("Error: malloc failed in vector_create\n");
        exit(1);
    }
    s->size = 0;
    s->top = NULL;
    return s;
}
void stack_destroy(Stack* s) {
    Node* curr = s->top;
    while (curr) {
        Node* next = curr->next;
        free(curr);
        curr = next;
    }
    free(s);
}
//插入
void stack_push(Stack* s, E val) {
    Node* new_node = malloc(sizeof(Node));
    if (!new_node) {
        printf("Error: malloc failed in add_before_head\n");
        exit(1);
    }

    new_node->data = val;
    new_node->next = s->top;
    s->top = new_node;

    s->size++;
}
E stack_pop(Stack* s) {
    if (s->size == 0)
    {
        printf("size=%d!", s->size);
        exit(1);
    }
Node* curr=s->top; E element
= curr->data; s->top = curr->next; s->size--;
free(curr); } E stack_peek(Stack
* s) {
if (s->size == 0)
    {
        printf("size=%d!", s->size);
        exit(1);
    }
    return s->top->data;
}
bool stack_empty(Stack* s)
{
return !(s->size); }

 

posted @ 2024-05-03 20:42  Uiney  阅读(6)  评论(0编辑  收藏  举报