HungryPuppy
HungryPuppy

Reputation: 3

Pop from a Single Linked List Implementation of a Stack C++

I have two functions to pop() in a single-linked list stack. But can't figure out why one is more correct than the other.

POP1:
X = head;
head = head->getNext();
return X;

POP2:
head = head->getNext();
X = head;
return X;

My answer is POP1, but I'm not sure why POP2 would be incorrect. Thanks for any help you can give me.

Upvotes: 0

Views: 78

Answers (2)

paper.plane
paper.plane

Reputation: 1197

Suppose the list looks like

A -> B -> C -> D -> NULL at this point head=A

So, functionality should remove and return A from the list. Lets see what are POP1 and POP2 doing.

POP1:

X = A;
head = B;
return A; 

At this point list will look like B -> C -> D -> NULL with head pointing to B. And the return value is A. All looks good.

POP2:

head = B;
X = B;
return B; 

At this point list will look like B -> C -> D -> NULL with head also pointing to B. But wait! its returning B instead of A.

Hope this clarifies.

Upvotes: 0

John3136
John3136

Reputation: 29265

Because in POP2 you remove the item from the top of the stack, throw it away (i.e. don't return it) and then you return the current top of the stack (which was actually the second item when you started).

Upvotes: 2

Related Questions