题目:顺序栈的实现+编写程序,构造一个空栈,定义入栈函数、出栈函数、栈中元
1个回答
关注
展开全部
亲,你好,很高兴为你解答,以下就是你需要的程序class SeqStack: def __init__(self, capacity): self.capacity = capacity self.stack = [] def is_empty(self): return len(self.stack) == 0 def is_full(self): return len(self.stack) == self.capacity def push(self, item): if self.is_full(): print("Stack is full. Cannot push item.") else:
咨询记录 · 回答于2023-06-17
题目:顺序栈的实现+编写程序,构造一个空栈,定义入栈函数、出栈函数、栈中元
亲,你好,很高兴为你解答,以下就是你需要的程序class SeqStack: def __init__(self, capacity): self.capacity = capacity self.stack = [] def is_empty(self): return len(self.stack) == 0 def is_full(self): return len(self.stack) == self.capacity def push(self, item): if self.is_full(): print("Stack is full. Cannot push item.") else:
题目:顺序栈的实现编写程序,构造一个空栈,定义入栈函数、出栈函数、栈中元素显示函数,使程序能完成入栈、出栈、并显示栈中数据元素。(也可自己添加其他操作,如取栈顶元素等)
完整的,用C语言
亲,你好,以下是使用 C 语言实现顺序栈的示例程序:
#include #include #define MAX_SIZE 100typedef struct { int data[MAX_SIZE]; int top;} SeqStack;// 初始化栈void initStack(SeqStack *stack) { stack->top = -1;}
// 判断栈是否为空bool isEmpty(SeqStack *stack) { return stack->top == -1;}// 判断栈是否已满bool isFull(SeqStack *stack) { return stack->top == MAX_SIZE - 1;}// 入栈操作void push(SeqStack *stack, int item) { if (isFull(stack)) { printf("Stack is full. Cannot push item.\n"); } else { stack->data[++(stack->top)] = item; }}
// 出栈操作int pop(SeqStack *stack) { if (isEmpty(stack)) { printf("Stack is empty. Cannot pop item.\n"); return -1; } else { return stack->data[(stack->top)--]; }}
// 显示栈中元素void displayStack(SeqStack *stack) { if (isEmpty(stack)) { printf("Stack is empty.\n"); } else { printf("Stack elements: "); for (int i = stack->top; i >= 0; i--) { printf("%d ", stack->data[i]); } printf("\n"); }}
int main() { SeqStack stack; initStack(&stack); push(&stack, 1); push(&stack, 2); push(&stack, 3); push(&stack, 4); displayStack(&stack); // 输出:Stack elements: 4 3 2 1 int item = pop(&stack); printf("Popped item: %d\n", item); // 输出:Popped item: 4 displayStack(&stack); // 输出:Stack elements: 3 2 1 return 0;}