[英]Pop from a Single Linked List Implementation of a Stack C++
I have two functions to pop() in a single-linked list stack. 我在单链接列表堆栈中有两个函数pop()。 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. 我的答案是POP1,但是我不确定POP2为什么不正确。 Thanks for any help you can give me.
感谢你给与我的帮助。
因为在POP2中,您从堆栈顶部删除了该项目,将其丢弃(即不退回),然后返回了堆栈的当前顶部(实际上是启动时的第二个项目)。
Suppose the list looks like 假设列表看起来像
A -> B -> C -> D -> NULL
at this point head=A
A -> B -> C -> D -> NULL
此时head=A
So, functionality should remove and return A
from the list. 因此,功能应从列表中删除并返回
A
Lets see what are POP1 and POP2 doing. 让我们看看POP1和POP2在做什么。
POP1: 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. 此时列表看起来像
B -> C -> D -> NULL
,头指向B。返回值为A。一切看起来都很好。
POP2: 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! 此时列表看起来像
B -> C -> D -> NULL
,头也指向B。但是等等! its returning B instead of A. 其返回的B而不是A。
Hope this clarifies. 希望这可以澄清。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.