我的第3个堆栈从第1和第2个堆栈以相反的顺序打印出来

时间:2014-02-14 00:26:34

标签: c++ linked-list stack

下面我将显示运行时程序的输出: enter image description here

现在我将展示预期的输出:

enter image description here

我将展示我教授的代码正在实现的功能,或者更确切地说是"复制构造函数"或者我在下面做的过载功能:

void operator=(const Stack& s)
    {
        if (s.top == NULL){
            num_items = 0;
            top = NULL;}
        else
        {
            top = new Node;
            top->data = s.top->data;
            Node* newP = top;
                num_items = 1;
                for(Node* curr = s.top->link; curr != NULL; curr = curr->link)

                {
                    if(num_items != MAX_SIZE)
                    {
                    newP->link = new Node;
                    newP = newP->link;
                    newP->data = curr->data;
                    ++num_items;
                    }
                }
        }
    }

最后,我将展示使用此功能的代码,我的导师代码:

    Stack<int> s3;
s3 = s3 + s2;
cout << "*declare s3 as a copy of s2 (stack s3 = s2)\ns3=" << s3 << endl; // copy constructor (=)
cout << "s3.Size()=" << s3.Size() << endl;
cout << "s3.IsEmpty()=" << ((s3.IsEmpty()) ? "T" : "F") << endl;
cout << "s3.IsFull()=" << ((s3.IsFull()) ? "T" : "F") << endl;
cout << "s3.Peek()=" << s3.Peek() << endl;
cout << endl;

我尝试了各种各样的事情,例如制作一个机器人指针试图找到堆栈底部的位置然后将其打印出来,但它似乎没有工作或我写了它不正确。

根据要求,这是运营商+代码:

    Stack operator+(const Stack& s) const
    {
        // copy the first list
        Stack t = *this;
        Stack u = *this;
        Node *n = s.top;

        // iterate through the second list and copy each element to the new list
        while (n != NULL && !t.IsFull())
        {
            t.Push(n->data);
            u.Push(n->data);
            n = n->link;
        }

        return u;
    }

1 个答案:

答案 0 :(得分:0)

无论如何,您似乎没有正确遵循Caleb的建议:

  

您正在将项目从s顶部推送到t,这意味着   s中的项目将显示在t上,但与之相反   他们在s。 [...]另一个仅使用堆栈操作的选项   是先将s一次推回到t上   中间堆栈,然后按下t再次反转。

u将是您的中间堆栈,// Populate the intermediate stack while (n != NULL && !t.IsFull()) { t.Push(n->data); n = n->link; } // Begin popping the intermediate stack // into the resulting stack n = t.top; while (n != NULL && !t.IsEmpty()) { u.Push(n->data); t.Pop(); n = t.top; } 将包含正确顺序的项目。将您的代码更改为以下内容:

operator=

另外,为了修正错误的尺寸,请使用其他问题中的代码。用following替换当前的Stack& operator=( const Stack& rhs ){ // call this->clear() to avoid memory leak if( rhs.top == NULL ){ top = NULL; return *this; } Node** store = &top; for( Node* curr = rhs.top; curr != NULL; curr = curr->link ){ Node* newNode = new Node; num_items++; newNode->data = curr->data; *store = newNode; store = &newNode->link; } return *this; } 代码可解决问题:

*declare s3 as a copy of s2 (stack s3 = s2)
s3=81 64 49 36 25 16 9 4 1 0 
s3.Size()=10
s3.IsEmpty()=F
s3.IsFull()=F
s3.Peek()=81

Live Example

输出:

{{1}}