Talk:Stack (abstract data type)

Wiki Education Foundation-supported course assignment
This article was the subject of a Wiki Education Foundation-supported course assignment, between 22 January 2020 and 14 May 2020. Further details are available on the course page. Peer reviewers: Wintersfire.

Above undated message substituted from Template:Dashboard.wikiedu.org assignment by PrimeBOT (talk) 10:06, 17 January 2022 (UTC)

Rename
I think this article should be named stack (computer science) since the concept of stack is used other than making computer software? Any objection? -- Taku 00:47, 6 Sep 2003 (UTC)


 * Stack (computing)? Nice, generic term... Includes CS and software dev't too. Dysprosia 00:49, 6 Sep 2003 (UTC)


 * It is fine too. Any other thoughts?

Merge
(to Martin) Hi, I see you merged stack pointer into Stack. Are you sure it's not an important enough idea to merit a separate article? There are a number of pages that link to stack pointer (and I was about to add a few more :-). Noel 20:04, 18 Oct 2003 (UTC)


 * Prove me wrong and write a long and well-written article on a stack pointer if you like.. but the version I merged didn't seem worth a seperate article. Martin 22:29, 20 Oct 2003 (UTC)

Image
I made an image for the german pendant to a stack (Kellerspeicher), perhaps you want to include it here. Is there a possibility to reuse the one from there or does it need a second upload? TRauMa, 2003-11-26


 * [[Image:Stack demo.png|left]]

I made my own stack image because I have a hard time seeing the one that is currently in the article (the contrast of the different shades of blue makes it hard for me to see the edges). The different layers are slightly transparent to make it more apparent that there are different layers. Is this acceptable? [[User:Aranel|Aranel ("Sarah")]] 17:27, 25 Oct 2004 (UTC)

LIFO / FIFO ?
Are all stacks LIFO? Aren't there FIFO stacks too? BradGad (Talk) 21:55, 21 Mar 2005 (UTC)


 * A "FIFO stack" would be a queue, I believe. anetor 07:45 07 Apr 2005 (PDT)


 * "FIFO" refers to a queue. cslave 21 Sept 2005

Stack (computing) merge with Stack-Based Memory Allocation
I believe Stack-Based Memory Allocation should be merged into this article because most of the information is redundant. Thoughts? --Vanished user 1029384756 15:08, 2 August 2005 (UTC)


 * Agreed. -- Taku 22:58, August 2, 2005 (UTC)


 * I Second -- cslave 21 Sept, 2005


 * The Stack-Based Memory Allocation article is total crap and should be deleted. -- John Tsiombikas 15 oct. 2005


 * Stack-Based Memory Allocation is an architecture article and thus is juxtaposed against Heap-Based Memory Allocation. The article here is about a more implementation-free stack and Stack machine describes a stack as a device unto itself. All three perspectives are useful, and Stack pointer aligns more with the architechture area. Hackwrench 01:38, 6 November 2005 (UTC)

Rotate method?
What is this rotate method for? What languages implement it? its not in the standard java lib...


 * Stack manipulation beyond pushing and popping is very useful in stack-oriented languages. Also, some dialects of Lisp will rotate on lists. Tsowell 11:40, 10 October 2006 (UTC)


 * The rotation visualization is confusing because it uses the same values in what look like different positions to contrast the visualization. The stack data is described by numerical position and the right-rotate process is described as, "right rotate will move the first element to the third position, the second to the first and the third to the second". A purely numerical representation of data items in a stack could be viewed as insufficient because the positions and the data items would both be represented numerically, thus easily confusing the reader. While the visualization IS equivalent, it is overly complex because it requires the reader to decipher the initial positioning by comparing the two data flows without indication of top to bottom or right to left priorities.


 * This is the current example:

apple                                                      banana banana                ==right rotate==>     cucumber cucumber                                               apple


 * and

cucumber banana apple ==right rotate==>  apple cucumber banana


 * Pure numeric representation would work as long as the article stated that the numbers were values within the stack and not indicative of the actual address within the stack. So the examples could be:

Bottom Up (Top to bottom):

1                          2 2 right rotate =>  3 3                          1

Left to Right:

3 2 1 == right rotate == > 1 3 2


 * Both of the designations in the paragraph above the visualization become misleading without an indication of direction. When most people think about left to right they assume they will read 0 1 2 3 from left to right on the page. The same applies to the term bottom up.


 * As defined in the article, the first and second positions rotate, then the second and third positions rotate. An animated diagram may be better.


 * As it is, ROL 1 2 3 > 2 3 1 works fine for the example, but when you get into a larger stack what happens? Does 1 2 3 4 5 6 rotate each item in series? 2 3 4 5 6 1 ?


 * Why not define it as: "Right Rotate moves the first item to the last position". If it functions as described it will always do that. The fact that it seems to be explained in terms of a sequential rotation involving two items at a time with the accompanying visualizations seems like a way to make the simple overly complex.


 * An example using the 6502 processor (motorola) is found here: http://www.atariarchives.org/roots/chapter_9.php (that would also cover early Apple Machines).

Peak?
Is this anything more than a falsely-justified spelling error? I can't find any such usage on Google. "Top", on the other hand, is a fairly widely-used alternative to "peek". Tsowell 11:40, 10 October 2006 (UTC)


 * As stated, the term 'peak' isn't a spelling error. Here is source found on the second page of google, searching for 'stack peak': http://www-db.stanford.edu/~burback/containers/stack.cpp


 * The function is meant to show the peak (top, acme, etc) of the stack without removing and returning it.


 * There have been many terms used to describe this, I prefer 'peak', but if you feel 'top' should be added, I wouldnt' have any objections.


 * On an off note, I do ask that people not edit things to change 'peak' to 'peek', since 'peak' is mentioned, it is a bit of an inane edit.


 * Reikon 23:02, 16 October 2006 (UTC)


 * Methods/functions are, by convention, verbs, just as objects are nouns. Therefore, 'peek' is better than 'peak' or 'top'. 'peak' also suggests a root of a tree (peak of a mountain?) to some in my experience. --David Federman 05:27, 24 November 2006 (UTC)


 * I strongly prefer peek to peak. I learned peek and top 20 years ago but this is the first time I've seen peak. When I Google'd (before reading this discussion) I found the stanford/burback source listed above - and I think it is a spelling error. I vote for peek as the primary spelling, with top (long established) and peak (reluctantly) as alternates. Manassehkatz 03:25, 4 December 2006 (UTC)


 * I found a textbook reference to TOP and adjusted the page accordingly. If anyone can find a citation (not just code on a webpage) earlier than 1984 showing PEEK or PEAK, please feel free to change. I also changed the pseudocode to pass data elements rather than nodes (data + pointer) as the push/pop/top functions should hide the pointer implementation details. Manassehkatz 15:31, 4 December 2006 (UTC)


 * Frankly, I've always appreciated peek (in this context) as meaning : look but don't touch anything which makes it a lot easier to explain to a student. Colin meier (talk) 18:28, 27 March 2009 (UTC)

The pop operation
It is stated that pop removes and returns the top element. This violates good design practice that inspection (return the top element) and mutation (remove the top element) should not be in the same operation. I suggest that the operation "top" return (a copy of) the top element and that the operation "pop" removes the top element without returning it. Comments? Corpus gigantus 07:19, 25 September 2007 (UTC)
 * Usually the elements are not "removed" or "deleted" anyway, the stack pointer is just decremented, as deleting is too wasteful of a computers resources... —Preceding unsigned comment added by 86.29.36.156 (talk) 23:20, 12 May 2008 (UTC)


 * Looking at what it says at the moment, I think the intention is to describe the theoretical concept of a stack – which has only two basic operations (push and pop) – rather than describing any particular implementation or what operations should be implemented from a good design practice point of view.
 * Indeed, some implementations, such as the C++ STL, do use pop for "remove the top element, without returning it". As such, the term has become ambiguous.  There ought to be two different terms for "remove and return the top element" and "remove the top element, without returning it".  Indeed, I've a vague recollection of having heard drop being used for the latter, but can't seem to find any evidence of this now. — Smjg (talk) 16:16, 27 August 2017 (UTC)
 * Adding to this, what you have called "good design practice" appears to me to be based on a particular design philosophy, rather than on practicality. From a practical point of view, the best practice may be to implement all three operations (top, pop and drop, per my earlier terminology).  Depending on the programming language and the stack implementation, pop may be more efficient than separate top and drop actions, but at the same time it's useful to have top for those situations where you just want to look at the top element and not remove it, and drop for those situations where you don't care about the element you're removing, to avoid the overhead of extracting it.
 * As a proof of concept, I have made a C++11 linked stack class on this principle. For pop, it takes advantage of rvalue references to extract the element without having to do a full copy, and for top it simply returns a reference.  Admittedly you may be able to do pop as

T item = std::move(stack.top); stack.drop;
 * but having pop in the class arguably makes it nicer when doing this as part of a more complex expression. — Smjg (talk) 09:55, 8 July 2023 (UTC)


 * Another thought: I first came across the terms push and pop in pushd and popd (in 4DOS, before coming across it in Unix shells and later in cmd.exe). Here, it seems pop has always had the "remove and return" semantics.  You could replace popd with separate topd (return without remove) and popd (remove without return) commands, but this would now break a lot of stuff.  But you could certainly keep popd as it is and implement topd and dropd in addition to this.


 * Yet another thought: One of my university lecturers used a Pez dispenser as an analogy for a stack. You can't take a Pez out of the dispenser and have it also remain in the dispenser, or make a Pez just vanish into thin air.  But I don't know if this or anything similar played a part in the development of the concept of a stack as a data structure or the coinage of the terms push and pop. — Smjg (talk) 10:43, 11 July 2023 (UTC)

Stacks usually grow down
In 28 years of programming Ive always known that stacks grew downwards and not upwards. This is certainly the case with many processors. With Rockwells 6500 family the stack always grew downwards and certainly when it comes to iPX86 upwards the stack grows downwards. It might only be semantics but it would be nice for the main page to be correct. —Preceding unsigned comment added by 83.146.9.122 (talk) 01:25, 11 November 2007 (UTC)
 * Stacks grow upwards like piling up of books, don't they? KnowledgeHegemonyPart2 (talk) 06:44, 3 April 2008 (UTC)


 * If I'm teaching students to implement stacks in arrays, etc, those stacks grow upward. I think currently upwards or downwards will depend on the implementation.Colin meier (talk) 18:30, 27 March 2009 (UTC)


 * Stacks can grow either up or down; in my 41 years of programming I've encountered both scenarios, even with different languages on the same hardware. It depends to some extent on what useful hardware instructions and addressing modes are available (if any).  There are two hardware instructions which may be significant in determining this choice: (a) machine-level subroutine call instruction, or (b) instruction used to push contents of a register onto a stack.  The available addressing modes may also be significant: if offsets from a base register must be positive then it is easier to have the stack grow upwards, but if offsets can be both negative and positive then the stack could just as easily grow in either direction. Murray Langton (talk) 04:32, 30 March 2009 (UTC)


 * What do "up" and "down" mean in the context of a processor architecture? Depending on the underlying implementation, they may be increasing or decreasing memory addresses, but these don't generally correspond to any physical direction.  Rather, when talking about a stack, "up" and "down" mean respectively towards and away from the end at which elements are pushed and popped, simply because it makes most sense when you consider a physical pile of things.  It seems you are using the terms "up" and "down" to mean something different, but it's unclear what.
 * Furthermore, this discussion seems to be about subroutine call stacks, which are typically sequential in memory, whereas the article is about the general concept of a stack as a data structure, which can have an array-based implementation, which would typically be sequential in memory, or a linked-list implementation, which would typically not. — Smjg (talk) 00:36, 23 December 2020 (UTC)

Postfix
— Preceding unsigned comment added by 121.97.230.167 (talk • contribs) 03:57, 24 January 2009 (UTC)

Convoluted
Any particular reason for using overly complicated code to illustrate what is really a very simple idea? There are plenty of examples on the web that illustrate a stack implementation in simpler terms. How about using an array based example that just stacks doubles (I'm avoiding the use of ++ operators because not everyone is familiar with the notation) ?

— Preceding unsigned comment added by Rhodydog (talk • contribs) 18:30, 19 April 2009 (UTC)

Lack of Abstraction
Considering a stack is a fundamental computer science data structure there seems to be a great lack of abstraction in this article. Shouldn't we define what a stack is before we start plunging into implementations?

/Definition/

Function signatures: init: -> Stack push: N x Stack -> Stack top: Stack -> (N U ERROR) remove: Stack -> Stack isempty: Stack -> B

(where N indicates a element (natural numbers in this sace), B indicates a boolean and U indicates set union)

Semantics top(init) = ERROR top(push(i,s)) = i   remove(init) = init remove(push(i, s)) = s   isempty(init) = true isempty(push(i, s)) = false

Jones "Systematic Software Development Using VDM"

ps. is there a bug with the wiki editor- none of the buttons work...

Salocin-yel (talk) 08:18, 7 June 2010 (UTC)

There are some problems, 5 of them to be precise, with this definition:

1° pop of empty stack results in ERROR, or Exception,

2° why one should consider stacks of natural numbers as only stacks? Replace N by E - any set of (stackable) elements,

3° one important property is missing, namely

Ax7)  not empty(s) → s=push(top(s), pop(s))

At present the six equalities cited above admit a paradoxical model: Let Stack be the set of all finite sequences of elements. Let's define

push(e, {e1, e2, ..., en})= {e,e,e1,e2, ... ,en} - we double e on input,

pop({e1,e2,e3, ...,en})={e3,...,en}

pop({e1,e2})= pop({e1})= the empty stack   or if you prefere init

pop(init) is undefined or Exception or ERROR

NOW, you can see that the property Ax7 does not hold because

top({e1,e2,e3, ...,en})=e1

pop({e1,e2,e3, ...,en})={e3,, ...,en} but

push(e1,{e3, ...,en})={e1,e1,e3, ...en}

Hence Ax7 is not deducible from the others axioms of stacks.

Comment One can easily write a class Stack, in say Java, such that it implements the example given above. No matter if Stack will implement stacks as array or linked LIFO list! End of comment

4° From where it follows that stack contain a finite number of elements?

It is possible to write a class Stack such that all 7 properties will be satisfied and still the program

while not empty(s) do s:=pop(s) od

will not terminate for some s instanceof Stack.

Funny? still it is true. Therefore, it seems reasonable to add a sentence any stack contains a finite sequence of elements as axiom Ax8.

5° I recommend to replace the word Semantics

by a phrase

Any structure that satisfies the properties Ax1 - Ax8 is a stack.

reference? ''Algorithmic Logic + SpecVer = the methodology for high integrity programming'', Grazyna Mirkowska, Andrzej Salwicki, Oskar Swida Fundamenta Informaticae XX (2013) 1–17 -- ́ Yes, I know it is like advertising my own results. However it is the truth about stacks. Check it or throw it. Andrzej Salwicki (talk) 09:35, 16 September 2014 (UTC)

The "Applications" section should be split.
It's far too long and it looks like splitting it up could be done at the same time as general cleanup. I'll go through each sub-section...


 * 6.1 Converting a decimal number into a binary number
 * This could probably stay, it's fairly short.


 * 6.2 Towers of Hanoi
 * The bulk of this should be moved into Towers of Hanoi and/or merged with the algorithms described there. A few paragraphs describing the problem and why stacks are applicable to it should be left on this page, with a "main article" template link.


 * 6.3 Expression evaluation and syntax parsing
 * I haven't looked around for a page on this subject, but there probably is one; if not, there deserves to be one! It can then be summarized again in a few paragraphs with a "main article" template link to the existing/new page.


 * 6.4 Conversion of an Infix expression that is fully parenthesized into a Postfix expression
 * This sub-section could be merged with the existing/new page that the content under 6.3 would be moved to.


 * 6.5 Rearranging railroad cars
 * This seems short enough to keep on this page.


 * 6.6 Quicksort
 * This should be moved/merged with the Quicksort page, again with a summary and main article link.


 * 6.7 The Stock Span Problem
 * I'm not well versed in this subject, but it seems like another thing that could be moved to either a new page or an existing one, again with a summary and main article link.


 * 6.8 Runtime memory management
 * This is already summarized and main article linked, so it can be left as is. This is how most of the other sections should ideally be.

I'm putting this here rather than actually doing it because it's a huge amount of work and should probably be discussed further before anything is done, to avoid doing anything that would turn out to be unnecessary in the long run, and also because of course there are some sections I've suggested to be split for which target pages need to be identified if possible. ~  Keiji (iNVERTED)  ( Talk )  21:00, 18 November 2011 (UTC)
 * By the way, feel free to reply in-line with my comments on each section above, but please copypaste my signature there if you do to avoid it becoming a mess. ~  Keiji (iNVERTED)  ( Talk )  21:02, 18 November 2011 (UTC)

Thanks for your suggestions Keiji!! :) Actually i did make a new page, solely on Applications of Stack, not once, but twice, but that was deleted both the times.. So i had to suffice by putting up all the information here.. I did give the same reason for creating a new page, stating that this page is looking really messy, but that reason did not seem sufficient.. Nipun Bayas (talk) 14:09, 5 January 2012 (UTC)


 * Hi Nipun. I think the application section is&mdash;at least in its current form&mdash;is not suited for an encyclopedic article on stacks. It would be more appropriate for a textbook, such as the WikiBook on data structures. One or two of the applications could remain (parsing expression is a classical example of the use of stacks, so that would be a good choice), be would need to be made more concise and probably use pseudocode. —Ruud 18:06, 21 August 2012 (UTC)

It's absurdly long - this is a problem with Wikipedia - people can put more and more in, but try to take out the garbage and you're blocked because you're "vandalizing the article. — Preceding unsigned comment added by 75.79.3.43 (talk) 20:41, 16 May 2014 (UTC)

Went ahead and WP:BOLDly the  section. Having so many examples really doesn't make much sense, as it has been already explained above, and they can always be recovered from the revision history and transferred over to WikiBooks, for example. Hope everyone agrees. &mdash; Dsimic (talk | contribs) 09:20, 7 August 2014 (UTC)

incorrect step in expression-evaluation section?
I'd prefer if somebody more knowledgeable about this topic fixed this, but I think there may be a mistake in this section: Stack_(abstract_data_type). Under the "closing brackets" part, the step "Go to step (2.4)" seems wrong. It should be "Go to step (1)". You can't pop from the character stack unless you're ready to evaluate thanks to a closing parenthesis, right? Proxyma (talk) 04:04, 24 November 2013 (UTC)

Towers of Hanoi
Given (as stated) that there is a separate article on the algorithm, the lengthy text and numerous illustrations are way over the top - assuming this section should even be kept in the article.

"The linked-list implementation is equally simple and straightforward. "
Seriously? - double indirection is as simple and straightforward as single indirection.

The push and pop code both call an alleged function called empty - no such C built-in.

@David Eppstein, cf. Turing
Apropos Turing and the sentence I had removed – like I wrote – subroutines were already implemented practically in the Z4 – which does not mean, that Zuse characterized the stack data structure – in the same way one has to ask – when Turing speaks about subroutines using the words bury /unbury – does he describe the stack data structure? If so, could it be cited? Could it be clarified? The way it’s in the article now makes no sense. 87.159.108.183 (talk) 10:46, 26 October 2014 (UTC)

The "Hardware stacks" section should be merged into Call stack
213.149.62.35 (talk) 01:16, 28 March 2017 (UTC)

We got some problems with Hardware Section
From the article:

"Basic architecture of a stack

A typical stack is an area of computer memory with a fixed origin and a variable size. Initially the size of the stack is zero. A stack pointer, usually in the form of a hardware register, points to the most recently referenced location on the stack; when the stack has a size of zero, the stack pointer points to the origin of the stack.

The two operations applicable to all stacks are:

a push operation, in which a data item is placed at the location pointed to by the stack pointer, and the address in the stack pointer is adjusted by the size of the data item; a pop or pull operation: a data item at the current location pointed to by the stack pointer is removed, and the stack pointer is adjusted by the size of the data item. There are many variations on the basic principle of stack operations. Every stack has a fixed location, in memory, at which it begins. As data items are added to the stack, the stack pointer is displaced to indicate the current extent of the stack, which expands away from the origin.

Stack pointers may point to the origin of a stack or to a limited range of addresses either above or below the origin (depending on the direction in which the stack grows); however, the stack pointer cannot cross the origin of the stack." <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

May I presume that when it says Hardware Section we are talking assembler code or machine code ???

My experience is asm on the Z80. There are a few contradictions here pertaining to this particular domain.

First: points to the most recently referenced location on the stack; this is correct, though we call it the "top of the stack". Then: a push operation, in which a data item is placed at the location pointed to by the stack pointer, this is incorrect. I hope it is obvious that the SP must first be decremented to point at the next available address below the top-of-stack. As written, this operation will overwrite the word topping the stack.

Now we come to: Every stack has a fixed location,. On the Z80 the range of addresses occupied by the stack is fixed, provided that the stack area is not changed to a new location with the LD SP,nn, LD SP,HL or LD SP,(nn) instructions. It is common practice on the Z80 to switch stack areas for various reasons. In fact, sometimes it is imperative.

Now we come to: the stack pointer cannot cross the origin of the stack. On the Z80 the origin would be the initial value loaded into the SP register. And yes, on the Z80 it is indeed possible to POP words off the stack and thereby increment SP past the "origin". This is an underflow condition. Speaking of which, there more common occurrence is PUSHing too many words, causing an overflow. Yet this eventuality is not described in the article.

The Z80 can directly manipulate the SP using the INC SP and DEC SP instructions. HL can swap with (SP) using EX (SP),HL. The ADD HL,SP and LD SP,HL instructions are often used to perform arithmetic on the SP; we are not limited to immediate loads with absolute values. This is how the stack is modified in relative terms on the Z80, since it lacks a formal relative addressing mode for data loads. The article should address arithmetic done on the SP.

I feel the main problem is that too many editors have worked over this article, each attempting to describe in too general a way the various idiosyncracies of different processors and languages. It's a real mess! Each particular situation should be separated and sorted out severally. These examples I have cited are just the tip of this article's iceberg...this is just too confusing for somebody relatively new who doesn't know how to tease out the various cross-purposes of each section. IMO.Wikkileaker (talk) 21:37, 14 July 2020 (UTC)

Move discussion in progress
There is a move discussion in progress on Talk:Associative array which affects this page. Please participate on that page and not in this talk page section. Thank you. —RMCD bot 00:32, 27 January 2022 (UTC)

India Education Program course assignment
This article was the subject of an educational assignment at College Of Engineering Pune supported by Wikipedia Ambassadors through the India Education Program&#32;during the 2011 Q3 term.&#32;Further details are available on the course page.

The above message was substituted from by PrimeBOT (talk) on 19:55, 1 February 2023 (UTC)

Too much "what", not enough "why"
This article dives into the details of what a stack is, but doesn't clearly explain why a stack might be preferable to other data structures such as a queue. I am not a computer scientist so don't know the correct way of stating it, but it's something like "stacks are useful when you have some result A that depends on result B, which in turn depends on C. You need some way of remembering where you were in the calculation of A, while you go off and calculate B, and then C, before coming back to B, and then A." You can't do that with a queue, because when you've finished C you'll come straight back to A before you have done B. — Preceding unsigned comment added by 80.47.212.205 (talk) 21:28, 7 November 2023 (UTC)

"Stack (computer science)" listed at Redirects for discussion
The redirect [//en.wikipedia.org/w/index.php?title=Stack_(computer_science)&redirect=no Stack (computer science)] has been listed at redirects for discussion to determine whether its use and function meets the redirect guidelines. Readers of this page are welcome to comment on this redirect at  until a consensus is reached. — Panamitsu (talk) 01:09, 15 October 2023 (UTC)