#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); } E element = s->top->data; s->top = s->top->next; s->size--; } E stack_peek(Stack* s) { return s->top->data; } bool stack_empty(Stack* s) { return !(s->size); }
标签:node,Node,自存,top,Stack,C语言,stack,size From: https://www.cnblogs.com/Uiney117/p/18171599