簡體   English   中英

我的第3疊從我的第1疊和第2疊開始以相反的順序打印

[英]My 3rd stack is printing out in reverse order from my 1st and 2nd stack

下面,我將顯示運行時程序的輸出: 在此處輸入圖片說明

現在,我將顯示預期的結果:

在此處輸入圖片說明

我將展示我教授的代碼正在實現的功能,或者是我在下面創建的“復制構造函數”或重載函數:

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

無論如何,看來您沒有正確遵循Caleb的建議:

您將項目從s的頂部推到t ,這意味着s的項目將出現在t ,但與它們在ss順序相反。 [...]僅使用堆棧操作的另一種選擇是,首先通過一次將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=代碼可解決此問題:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM