啸山笔记 - C
type: channel
link: https://www.lentech.site/category/C/
items: 栈的模拟（大学程序设计作业）

栈的模拟（大学程序设计作业）
type: item
date: 2022-03-26T16:09:00+00:00
description: Cstruct#include "stdio.h" #include "stdlib.h" struct node { int nodeVal; struct node *preNode; struct node *nextNode; }; struct stack { int stackSize; struct node *stackNode; }; struct stack *initStack() { struct stack *tmpStack = (struct stack *)malloc(sizeof(struct stack)); (*tmpStack).stackNode = (struct node *)malloc(sizeof(struct node)); (*tmpStack).stackSize = 0; return tmpStack; } int stackPush(struct stack *tmpStack, int tmpVal) { ++(*tmpStack).stackSize; (*(*tmpStack).stackNode).nextNode = (struct node *)malloc(sizeof(struct node)); (*(*(*tmpStack).stackNode).nextNode).preNode = (*tmpStack).stackNode; (*(*(*tmpStack).stackNode).nextNode).nodeVal = tmpVal; (*tmpStack).stackNode = (*(*tmpStack).stackNode).nextNode; (*(*tmpStack).stackNode).nextNode = NULL; return 0; } int getStackTop(struct stack *tmpStack) { if ((*tmpStack).stackSize != 0) return (*(*tmpStack).stackNode).nodeVal; return EOF; } int stackPop(struct stack *tmpStack) { if ((*tmpStack).stackSize == 0) return EOF; (*tmpStack).stackNode = (*(*tmpStack).stackNode).preNode; free((*(*tmpStack).stackNode).nextNode); --(*tmpStack).stackSize; return 0; } int getStackSize(struct stack tmpStack) { return tmpStack.stackSize; } int stackIfEmpty(struct stack tmpStack) { return tmpStack.stackSize == 0; } void stackShow(struct stack *tmpStack) { printf("stack: "); if ((*tmpStack).stackSize == 0) { printf("NULL\n"); return; } struct node *currentNode = (*tmpStack).stackNode; int tmpSize = (*tmpStack).stackSize; while (tmpSize > 0) { printf("%d\t", (*currentNode).nodeVal); currentNode = (*currentNode).preNode; --tmpSize; } printf("\n"); } int deleteStack(struct stack *tmpStack) { free(tmpStack); return 0; } int main() { struct stack *tmpStack = initStack(); stackShow(tmpStack); stackPush(tmpStack, 1); stackPush(tmpStack, 2); stackPush(tmpStack, 3); stackShow(tmpStack); stackPop(tmpStack); stackShow(tmpStack); stackPop(tmpStack); stackShow(tmpStack); stackPush(tmpStack, 4); stackShow(tmpStack); stackPop(tmpStack);…