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

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

本文关键字:链表 堆栈 实现 C++ 学习      更新时间:2023-10-16

我想使用堆栈实现链表。这是我的班级:

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;
}

截至目前,推送和窥视似乎正在起作用,但流行不起作用。请帮忙。我想保持所有实现/风格相同,我只想修复错误以使其工作。

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

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