I'm confused on how i'd go about overloadi

2019-09-06 20:43发布

问题:

First of all, i know how to do this using a linked list in general, which i will paste below:

    List operator+(const List& l) const
    {
        // copy the first list
        List t = *this;
        Node *n = l.head;

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

        return t;
    }

Now in my Stack i have something that looks like this:

Stack operator+(const Stack& s) const
    {
        // copy the first list
        Stack t = *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);
            n = n->link;
        }

        return t;
    }

My question i guess would be, would this be the right way of going about it? And i'd like to apologize in advance if the Title of this question isn't very clear, i had trouble even figuring out how to word it.

Edit:

I came out with a loop looking like this in reference to Caleb's answer:

        Stack t = *this;
        Stack u = *this;
        Node *n = s.top;
while (n != NULL && !t.IsFull())
        {
            t.Push(n->data);
            u.Push(n->data);
            n = n->link;
        }

        return t;
    }

回答1:

would this be the right way of going about it?

You're pushing items from the top of s onto t, and that means that the items from s will appear on t, but in reverse order compared to what they were on s. If that's what you want, your implementation is fine, but it's hard to think of a situation where that behavior would be useful or expected. Pushing from the bottom of s to the top would fix the problem, but that's not an option if you have to stick strictly to stack operations. Another option that uses only stack operations is to first reverse s by pushing them one at a time onto an intermediate stack, and then reverse again by pushing onto t.