使用链接列表的cpp程序堆栈

时间:2019-06-19 19:56:47

标签: c++

我试图使用链表实现堆栈,我创建了一个全局变量 head=NULL并创建了push和pop函数,但是我观察到第一次查询(即第一个值被推入时)的头部正确指向了它 但是,当我将控制权转到main时,它又返回推入了,然后在执行当前值之前,我检查了head值已更改为某些垃圾值。

void MyStack::push(int x) {
    StackNode temp(x);
    if (head == NULL) {
        head = &temp;
    }
    else {
        temp.next = head;
        head->next = &temp;
    }
}
/* The method pop which return the element
  poped out of the stack*/
int MyStack::pop() {
    if (head == NULL)return -1;
    else if (head->next == NULL) {
        int t = head->data;
        head = NULL;
        return t;
    }
    else {
        int t = head->data;
        head = head->next;
        return t;
    }
}

我的主程序

#include <iostream>

using namespace std;
struct StackNode {
    int data;
    StackNode *next;
    StackNode(int a) {
        data = a;
        next = NULL;
    }
};
StackNode* head = NULL; /// Global variable to hold linked list
class MyStack {
private:
    StackNode *top;
public:
    void push(int);
    int pop();
    MyStack() { top = NULL; }
};
int main() {
    int T;
    cin >> T;
    while (T--) {
        MyStack *sq = new MyStack();
        int Q;
        cin >> Q;
        while (Q--) {
            int QueryType = 0;
            cin >> QueryType;
            if (QueryType == 1) {
                int a;
                cin >> a;
                sq->push(a);
            }
            else if (QueryType == 2) {
                cout << sq->pop() << " ";
            }
        }
        cout << endl;
    }
}



/*This is a function problem.You only need to complete the function given below*/
/*
The structure of the node of the stack is
struct StackNode
{
    int data;
    StackNode *next;
    StackNode(int a)
    {
        data = a;
        next = NULL;
    }
};
// And this is structure of MyStack
class MyStack {
private:
StackNode *top;
public :
    void push(int);
    int pop();
    MyStack()
    {
        top = NULL;
    }
};
/* The method push to push element
   into the stack */

void MyStack::push(int x) {
    StackNode temp(x);
    if (head == NULL) {
        head = &temp;
    }
    else {
        temp.next = head;
        head->next = &temp;
    }
}
/* The method pop which return the element
  poped out of the stack*/
int MyStack::pop() {
    if (head == NULL)return -1;
    else if (head->next == NULL) {
        int t = head->data;
        head = NULL;
        return t;
    }
    else {
        int t = head->data;
        head = head->next;
        return t;
    }
}

problem link

0 个答案:

没有答案