Push, which adds an element to the collection, and
Pop, which removes the most recently added element.
Additionally, apeek operation can, without modifying the stack, return the value of the last element added. The namestack is ananalogy to a set of physical items stacked one atop another, such as a stack of plates.
The order in which an element added to or removed from a stack is described aslast in, first out, referred to by the acronymLIFO.[nb 1] As with a stack of physical objects, this structure makes it easy to take an item off the top of the stack, but accessing adatum deeper in the stack may require removing multiple other items first.[1]
Considered a sequential collection, a stack has one end which is the only position at which the push and pop operations may occur, thetop of the stack, and is fixed at the other end, thebottom. A stack may be implemented as, for example, asingly linked list with a pointer to the top element.
A stack may be implemented to have a bounded capacity. If the stack is full and does not contain enough space to accept another element, the stack is in a state ofstack overflow.
Stacks entered the computer science literature in 1946, whenAlan Turing used the terms "bury" and "unbury" as a means of calling and returning from subroutines.[2][3]Subroutines and a two-levelstack had already been implemented inKonrad Zuse'sZ4 in 1945.[4][5]
Stacks are often described using the analogy of a spring-loaded stack of plates in a cafeteria.[16][1][17] Clean plates are placed on top of the stack, pushing down any plates already there. When the top plate is removed from the stack, the one below it is elevated to become the new top plate.
In many implementations, a stack has more operations than the essential "push" and "pop" operations. An example of a non-essential operation is "top of stack", or "peek", which observes the top element without removing it from the stack.[18] Since this can be broken down into a "pop" followed by a "push" to return the same data to the stack, it is not considered an essential operation. If the stack is empty, an underflow condition will occur upon execution of either the "stack top" or "pop" operations. Additionally, many implementations provide a check if the stack is empty and an operation that returns its size.
A stack can be easily implemented either through anarray or alinked list, as it is merely a special case of a list.[19] In either case, what identifies the data structure as a stack is not the implementation but the interface: the user is only allowed to pop or push items onto the array or linked list, with few other helper operations. The following will demonstrate both implementations usingpseudocode.
An array can be used to implement a (bounded) stack, as follows. The first element, usually at thezero offset, is the bottom, resulting inarray[0] being the first element pushed onto the stack and the last element popped off. The program must keep track of the size (length) of the stack, using a variabletop that records the number of items pushed so far, therefore pointing to the place in the array where the next element is to be inserted (assuming a zero-based index convention). Thus, the stack itself can be effectively implemented as a three-element structure:
structure stack: maxsize : integer top : integer items : array of item
Similarly,pop decrements thetop index after checking for underflow, and returns the item that was previously the top one:
procedure pop(stk : stack):if stk.top = 0: report underflow errorelse: stk.top ← stk.top − 1 r ← stk.items[stk.top]return r
Using adynamic array, it is possible to implement a stack that can grow or shrink as much as needed. The size of the stack is simply the size of the dynamic array, which is a very efficient implementation of a stack since adding items to or removing items from the end of a dynamic array requires amortized O(1) time.
Another option for implementing stacks is to use asingly linked list. A stack is then a pointer to the "head" of the list, with perhaps a counter to keep track of the size of the list:
structure frame: data : item next : frame or nil
structure stack: head : frame or nil size : integer
Some languages, such asPerl,LISP,JavaScript andPython, make the stack operations push and pop available on their standard list/array types. Some languages, notably those in theForth family (includingPostScript), are designed around language-defined stacks that are directly visible to and manipulated by the programmer.
The following is an example of manipulating a stack inCommon Lisp (">" is the Lisp interpreter's prompt; lines not starting with ">" are the interpreter's responses to expressions):
>(setfstack(list'a'b'c));; set the variable "stack"(ABC)>(popstack);; get top (leftmost) element, should modify the stackA>stack;; check the value of stack(BC)>(push'newstack);; push a new top onto the stack(NEWBC)
Several of theC++ Standard Library container types havepush_back andpop_back operations with LIFO semantics; additionally, thestack template class adapts existing containers to provide a restrictedAPI with only push/pop operations. PHP has anSplStack class. Java's library contains aStack class that is a specialization ofVector. Following is an example program inJava language, using that class.
importjava.util.Stack;classStackDemo{publicstaticvoidmain(String[]args){Stack<String>stack=newStack<String>();stack.push("A");// Insert "A" in the stackstack.push("B");// Insert "B" in the stackstack.push("C");// Insert "C" in the stackstack.push("D");// Insert "D" in the stackSystem.out.println(stack.peek());// Prints the top of the stack ("D")stack.pop();// removing the top ("D")stack.pop();// removing the next top ("C")}}
Some processors, such as thePDP-11,VAX, andMotorola 68000 series have addressing modes useful for stack manipulation. The following trivial PDP-11assembly source code pushes two numbers on a stack and adds them, leaving the result on the stack.
; R0 is assumed to point to a stack area; -(R0) pre-decrements stack pointer allocating item on stack; (R0)+ Post-increments stack pointer removing item on stack;MOV#12,-(R0) ; Push 12 on stackMOV#34,-(R0) ; push 34 on stackADD(R0)+,(R0); Pop 34 off stack and add to 12; leaving the result on the 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. Astack pointer (usually in the form of aprocessor 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:
Apush operation: the address in the stack pointer is adjusted by the size of the data item and a data item is written at the location to which the stack pointer points.
Apop orpull operation: a data item at the current location to which the stack pointer points is read, and the stack pointer is moved by a distance corresponding to the size of that 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 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. In other words, if the origin of the stack is at address 1000 and the stack grows downwards (towards addresses 999, 998, and so on), the stack pointer must never be incremented beyond 1000 (to 1001 or beyond). If a pop operation on the stack causes the stack pointer to move past the origin of the stack, astack underflow occurs. If a push operation causes the stack pointer to increment or decrement beyond the maximum extent of the stack, astack overflow occurs.
Some environments that rely heavily on stacks may provide additional operations, for example:
Duplicate: the top item is popped and then pushed twice, such that two copies of the former top item now lie at the top.
Peek: the topmost item is inspected (or returned), but the stack pointer and stack size does not change (meaning the item remains on the stack). This can also be called thetop operation.
Swap orexchange: the two topmost items on the stack exchange places.
Rotate (or Roll): then topmost items are moved on the stack in a rotating fashion. For example, ifn = 3, items 1, 2, and 3 on the stack are moved to positions 2, 3, and 1 on the stack, respectively. Many variants of this operation are possible, with the most common being calledleft rotate andright rotate.
Stacks are often visualized growing from the bottom up (like real-world stacks). They may also be visualized growing from left to right, where the top is on the far right, or even growing from top to bottom. The important feature is for the bottom of the stack to be in a fixed position. The illustration in this section is an example of a top-to-bottom growth visualization: the top (28) is the stack "bottom", since the stack "top" (9) is where items are pushed or popped from.
Aright rotate will move the first element to the third position, the second to the first and the third to the second. Here are two equivalent visualizations of this process:
apple bananabanana ===right rotate==> cucumbercucumber apple
A stack is usually represented in computers by a block of memory cells, with the "bottom" at a fixed location, and the stack pointer holding the address of the current "top" cell in the stack. The "top" and "bottom" nomenclature is used irrespective of whether the stack actually grows towards higher memory addresses.
Pushing an item on to the stack adjusts the stack pointer by the size of the item (either decrementing or incrementing, depending on the direction in which the stack grows in memory), pointing it to the next cell, and copies the new top item to the stack area. Depending again on the exact implementation, at the end of a push operation, the stack pointer may point to the next unused location in the stack, or it may point to the topmost item in the stack. If the stack points to the current topmost item, the stack pointer will be updated before a new item is pushed onto the stack; if it points to the next available location in the stack, it will be updatedafter the new item is pushed onto the stack.
Popping the stack is simply the inverse of pushing. The topmost item in the stack is removed and the stack pointer is updated, in the opposite order of that used in the push operation.
ManyCISC-typeCPU designs, including thex86,Z80 and6502, have a dedicated register for use as thecall stack stack pointer with dedicated call, return, push, and pop instructions that implicitly update the dedicated register, thus increasingcode density. Some CISC processors, like thePDP-11 and the68000, also havespecial addressing modes for implementation of stacks, typically with a semi-dedicated stack pointer as well (such as A7 in the 68000). In contrast, mostRISC CPU designs do not have dedicated stack instructions and therefore most, if not all, registers may be used as stack pointers as needed.
Theprogrammable pocket calculatorHP-42S from 1988 had, like nearlyall of the company's calculators of that time, a 4-level-stack and could display two of four values of the stack registers X, Y, Z, and T at the same time due to its two-line display, here X and Y. In later models like theHP-48, the number of levels was increased to be only limited by memory size.
Some machines use a stack for arithmetic and logical operations; operands are pushed onto the stack, and arithmetic and logical operations act on the top one or more items on the stack, popping them off the stack and pushing the result onto the stack. Machines that function in this fashion are calledstack machines.
Thex87floating point architecture is an example of a set of registers organised as a stack where direct access to individual registers (relative to the current top) is also possible.
Having the top-of-stack as an implicit argument allows for a smallmachine code footprint with a good usage ofbusbandwidth andcode caches, but it also prevents some types of optimizations possible on processors permittingrandom access to theregister file for all (two or three) operands. A stack structure also makessuperscalar implementations withregister renaming (forspeculative execution) somewhat more complex to implement, although it is still feasible, as exemplified by modernx87 implementations.
Sun SPARC,AMD Am29000, andIntel i960 are all examples of architectures that useregister windows within a register-stack as another strategy to avoid the use of slow main memory for function arguments and return values.
There is also a number of small microprocessors that implement a stack directly in hardware, and somemicrocontrollers have a fixed-depth stack that is not directly accessible. Examples are thePIC microcontrollers, theComputer CowboysMuP21, theHarris RTX line, and theNovixNC4016. At least one microcontroller family, theCOP400, implements a stack either directly in hardware or in RAM via a stack pointer, depending on the device. Many stack-based microprocessors were used to implement the programming languageForth at themicrocode level.
Calculators that employreverse Polish notation use a stack structure to hold values. Expressions can be represented in prefix, postfix or infix notations and conversion from one form to another may be accomplished using a stack. Many compilers use a stack to parse syntax before translation into low-level code. Most programming languages arecontext-free languages, allowing them to be parsed with stack-based machines.
Another important application of stacks isbacktracking. An illustration of this is the simple example of finding the correct path in a maze that contains a series of points, a starting point, several paths and a destination. If random paths must be chosen, then after following an incorrect path, there must be a method by which to return to the beginning of that path. This can be achieved through the use of stacks, as a last correct point can be pushed onto the stack, and popped from the stack in case of an incorrect path.
The prototypical example of a backtracking algorithm isdepth-first search, which finds all vertices of a graph that can be reached from a specified starting vertex. Other applications of backtracking involve searching through spaces that represent potential solutions to an optimization problem.Branch and bound is a technique for performing such backtracking searches without exhaustively searching all of the potential solutions in such a space.
A typical call stack, storing local data and call information for multiple levels of procedure calls. This stack grows downward from its origin. The stack pointer points to the current topmostdatum on the stack. A push operation decrements the pointer and copies the data to the stack; a pop operation copies data from the stack and then increments the pointer. Each procedure called in the program stores procedure return information (in yellow) and local data (in other colors) by pushing them onto the stack. This type of stack implementation is extremely common, but it is vulnerable tobuffer overflow attacks (see the text).
A number ofprogramming languages arestack-oriented, meaning they define most basic operations (adding two numbers, printing a character) as taking their arguments from the stack, and placing any return values back on the stack. For example,PostScript has a return stack and an operand stack, and also has a graphics state stack and a dictionary stack. Manyvirtual machines are also stack-oriented, including thep-code machine and theJava Virtual Machine.
Almost allcalling conventions—the ways in whichsubroutines receive their parameters and return results—use a special stack (the "call stack") to hold information about procedure/function calling and nesting in order to switch to the context of the called function and restore to the caller function when the calling finishes. The functions follow a runtime protocol between caller and callee to save arguments and return value on the stack. Stacks are an important way of supporting nested orrecursive function calls. This type of stack is used implicitly by the compiler to support CALL and RETURN statements (or their equivalents) and is not manipulated directly by the programmer.
Some programming languages use the stack to store data that is local to a procedure. Space for local data items is allocated from the stack when the procedure is entered, and is deallocated when the procedure exits. TheC programming language is typically implemented in this way. Using the same stack for both data and procedure calls has important security implications (see below) of which a programmer must be aware in order to avoid introducing serious security bugs into a program.
Severalalgorithms use a stack (separate from the usual function call stack of most programming languages) as the principaldata structure with which they organize their information. These include:
Graham scan, an algorithm for theconvex hull of a two-dimensional system of points. A convex hull of a subset of the input is maintained in a stack, which is used to find and remove concavities in the boundary when a new point is added to the hull.[20]
Part of theSMAWK algorithm for finding the row minima of a monotone matrix uses stacks in a similar way to Graham scan.[21]
All nearest smaller values, the problem of finding, for each number in an array, the closest preceding number that is smaller than it. One algorithm for this problem uses a stack to maintain a collection of candidates for the nearest smaller value. For each position in the array, the stack is popped until a smaller value is found on its top, and then the value in the new position is pushed onto the stack.[22]
Thenearest-neighbor chain algorithm, a method foragglomerative hierarchical clustering based on maintaining a stack of clusters, each of which is the nearest neighbor of its predecessor on the stack. When this method finds a pair of clusters that are mutual nearest neighbors, they are popped and merged.[23]
Some computing environments use stacks in ways that may make them vulnerable tosecurity breaches and attacks. Programmers working in such environments must take special care to avoid such pitfalls in these implementations.
As an example, some programming languages use a common stack to store both data local to a called procedure and the linking information that allows the procedure to return to its caller. This means that the program moves data into and out of the same stack that contains critical return addresses for the procedure calls. If data is moved to the wrong location on the stack, or an oversized data item is moved to a stack location that is not large enough to contain it, return information for procedure calls may be corrupted, causing the program to fail.
Malicious parties may attempt astack smashing attack that takes advantage of this type of implementation by providing oversized data input to a program that does not check the length of input. Such a program may copy the data in its entirety to a location on the stack, and in doing so, it may change the return addresses for procedures that have called it. An attacker can experiment to find a specific type of data that can be provided to such a program such that the return address of the current procedure is reset to point to an area within the stack itself (and within the data provided by the attacker), which in turn contains instructions that carry out unauthorized operations.
This type of attack is a variation on thebuffer overflow attack and is an extremely frequent source of security breaches in software, mainly because some of the most popular compilers use a shared stack for both data and procedure calls, and do not verify the length of data items. Frequently, programmers do not write code to verify the size of data items, either, and when an oversized or undersized data item is copied to the stack, a security breach may occur.
^Turing, Alan Mathison (1946-03-19) [1945].Proposals for Development in the Mathematics Division of an Automatic Computing Engine (ACE). (NB. Presented on 1946-03-19 before the Executive Committee of the National Physical Laboratory (Great Britain).)
^LaForest, Charles Eric (April 2007). "2.1 Lukasiewicz and the First Generation: 2.1.2 Germany: Konrad Zuse (1910–1995); 2.2 The First Generation of Stack Computers: 2.2.1 Zuse Z4".Second-Generation Stack Computer Architecture(PDF) (thesis). Waterloo, Canada:University of Waterloo. pp. 8, 11.Archived(PDF) from the original on 2022-01-20. Retrieved2022-07-02. (178 pages)
^Samelson, Klaus (1957) [1955]. Written at Internationales Kolloquium über Probleme der Rechentechnik, Dresden, Germany.Probleme der Programmierungstechnik (in German). Berlin, Germany:VEB Deutscher Verlag der Wissenschaften. pp. 61–68. (NB. This paper was first presented in 1955. It describes a number stack (Zahlenkeller), but names it linear auxiliary memory (linearer Hilfsspeicher).)
^Bauer, Friedrich Ludwig;Goos, Gerhard[in German] (1982).Informatik – Eine einführende Übersicht (in German). Vol. Part 1 (3 ed.). Berlin:Springer-Verlag. p. 222.ISBN3-540-11722-9.Die Bezeichnung 'Keller' hierfür wurde von Bauer und Samelson in einer deutschen Patentanmeldung vom 30. März 1957 eingeführt.
^Samelson, Klaus;Bauer, Friedrich Ludwig (1959). "Sequentielle Formelübersetzung" [Sequential Formula Translation].Elektronische Rechenanlagen (in German).1 (4):176–182.