链栈的实现主要包括链栈的定义、链栈的初始化、链栈的判空、链栈的入栈、链栈的出栈和链栈的取栈顶等操作。下面是一个简单的实现:

#include <iostream>

using namespace std;

// 定义链栈结构体
struct Node {
    int data;
    Node* next;
};

class LinkedStack {
private:
    Node* top; // 链栈的栈顶指针
public:
    // 初始化链栈
    LinkedStack() {
        top = NULL;
    }

    // 判断链栈是否为空
    bool isEmpty() {
        return top == NULL;
    }

    // 入栈操作
    void push(int data) {
        Node* newNode = new Node;
        newNode->data = data;
        newNode->next = top; // 将新节点指向栈顶节点
        top = newNode; // 更新栈顶指针
    }

    // 出栈操作
    void pop() {
        if (isEmpty()) {
            cout << "Stack is empty." << endl;
            return;
        }
        Node* temp = top;
        top = top->next; // 更新栈顶指针
        delete temp; // 释放内存
    }

    // 取栈顶元素
    int getTop() {
        if (isEmpty()) {
            cout << "Stack is empty." << endl;
            return -1;
        }
        return top->data;
    }
};

int main() {
    LinkedStack stack;

    stack.push(1);
    stack.push(2);
    stack.push(3);

    cout << "Top element: " << stack.getTop() << endl;

    stack.pop();
    stack.pop();

    cout << "Top element: " << stack.getTop() << endl;

    stack.pop();
    stack.pop();

    return 0;
}

注:链栈的入栈、出栈和取栈顶元素的时间复杂度均为O(1)。

链栈用c++怎么写

原文地址: https://www.cveoy.top/t/topic/bZiA 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录