How would I go about finding the first/bottom element 'pushed' into the linked list stack?

would I need to copy the stack, then pop the elements until I reach the first element?

I'm not even sure how I would go about doing this. The only thing I can think of is traversering the linked list, but how would that without traversing the entire list? Or would I copy the original list to a temp list, then pop elements off the stack until I reach the last one?

Here's what I have so far (this one attempts at traversing)

StackElement Stack::bottom(const Stack & original) const 
{
    bottomPtr = myTop, //myTop is top element on stack
    origPtr = original.myTop->next;

    if(!empty())
    {
        while(origPtr != 0)   
        {
              //THIS IS WHERE I'M STUCK, I DONT WANT TO TRAVERSE  
              //THE ENTIRE LIST
            return bottomPtr;
        }
    }
    else
    {
        cerr << "stack is empty -- returning garbage\n";
        StackElement * temp = new(StackElement);
        StackElement garbage = *temp;
        delete temp;
        return garbage;
    }
}

i don't think there is another way than to traverse the entire list.as the list is dynamic, we have traverse using pointers and hence traverse each node.:)

Add another pointer -- call it tail or something -- that keeps track of the last node. Then when you need the end of the list it will be easily available without taking the time to traverse the entire list.

This article has been dead for over six months. Start a new discussion instead.