【每日算法】AB1 基于数组的栈的实现

32 阅读1分钟

代码

#include <iostream>
#include <string.h>
using namespace std;

struct stack {
    long data[100001];
    int top;
} stack;

void init(struct stack& stack) {
    stack.top = 0;
}

void push(struct stack& stack, int a) {
    stack.data[stack.top] = a;
    stack.top ++;
}

int pop(struct stack& stack) {
    if (stack.top == 0) {
        return -1;
    } else {
        stack.top --;
        return stack.data[stack.top];
    }
}

int top(struct stack& stack) {
    if (stack.top == 0) {
        return -1;
    } else {
        return stack.data[stack.top - 1];
    }
}

int main() {
    int cnt;
    cin >> cnt;
    int data;
    string op;
    struct stack stack_;
    init(stack_);
    while (cnt--) { // 注意 while 处理多个 case
        cin >> op;
        if (op == "push") {
            cin >> data;
            push(stack_, data);
        } else if (op == "pop") {
            if (stack_.top == 0) {
                cout << "error" << endl;
            } else {
                int ret = pop(stack_);
                cout << ret << endl;
            }
        } else if (op == "top") {
            if (stack_.top == 0) {
                cout << "error" << endl;
            } else {
                int ret = top(stack_);
                cout << ret << endl;
            }
        }
    }
}

问题总结:

  1. 起初发现调用函数后栈成员的值并没有改变,才想起来形参和实参的区别: C程序函数参数会出现在两个地方:函数定义处(形参)、函数调用处(实参),进行函数调用时,形参入栈,实参赋值给形参,函数返回时,形参出栈。因此,如果想要改变main函数中定义的stack_的成员变量,仅把结构体赋值给形参是不够的,应该: ①将结构体的地址赋值给形参,这样函数才可以修改对应地址的变量的值。 ②或者,传引用(如以上代码),把对实参的引用传入函数,不会新建变量
  2. 段错误:又是它,这次是因为数组设太小了,好说,设大点就好了

复习知识点

  1. 函数传参:传值、传址、传引用
  2. 形参和实参