简体   繁体   中英

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

I want to implement a linked list using stack. Here is my class:

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

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

My implementation so far:

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

As of now, the push and peek seem to be working, but the pop does not work. Please help. I want to keep all the implementation/style the same, I just want to fix the error to make it work.

I think that you wrote the pop method wrong. You're inserting a new item. I hope this works.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM