目录
思维导图
01 栈的单链表实现:
用单链表实现栈
#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);
解答:
#define _CRT_SECURE_NO_WARNINGS
#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;
Stack* stack_create(void) {
Stack* sta= malloc(sizeof(Stack)); //申请栈
if (!sta) {
printf("error in stack_create\n");
exit(1);
}
//更新栈信息
sta->size = 0;
sta->top = NULL;
return sta;
}
void stack_destroy(Stack* s) {
free(s->top);
free(s);
}
void stack_push(Stack* s, E val) {
//新建结点,赋值
Node* newnode = malloc(sizeof(Node));
if (!newnode) {
printf("error in stack_push\n");
exit(1);
}
newnode->data = val;
newnode->next = s->top;
//更新栈信息
s->top = newnode;
s->size++;
}
E stack_pop(Stack* s) { //头删除
//记录top->next
//删除top,free
//new_top
Node* newtop = s->top->next;
E del = s->top->data;
free(s->top);
s->top = newtop;
//更新栈信息
s->size--;
return del;
}
E stack_peek(Stack* s) { //查看栈顶元素
return s->top->data;
}
bool stack_empty(Stack* s) {
if (s->size) {
return false;
}
return true;
}
int main(void) {
Stack* s = stack_create