学习在 C++ 中实现链表堆栈 class

Learning to implement a Linked List Stack class in C++

我想用栈实现一个链表。这是我的 class:

class LinkedListStack
{
public:
    LinkedListStack();
    void push(int x);
    void pop();
    int peek();

private:
    struct Node
    {
        int data;
        Node *next;
    };
    Node *head;
    Node *tail;
};

到目前为止我的实施:

LinkedListStack::LinkedListStack()
{
    m_headPtr = 0;
    m_tailPtr = 0;
}

void LinkedListStack::push(int x)
{
    struct Node* newNode = (struct Node*) malloc(sizeof(struct node));
    newNode->data = x;
    newNode->next = head;
    head = newNode;
}

void LinkedListStack::pop()
{
    struct Node* newNode = (struct Node*) malloc(sizeof(struct Node));
    newNode->data = NULL;
    newNode->next = head;
    head = newNode;
    delete newNode;
}

int LinkedListStack::peek()
{
    return head->data;
}

截至目前,push 和 peek 似乎有效,但 pop 无效。 请帮忙。我想让所有 implementation/style 保持不变,我只是想修复错误以使其正常工作。

我认为你把pop方法写错了。您正在插入一个新项目。 我希望这有效。

void LinkedListStack::pop()
{
    if (head != 0)
    {
        struct Node* newHead = head->next;
        delete head;
        head = newHead;
    }
}