what is stack and how to use it

Stacks and Queues

An array is a random access data structure, where each element tin exist accessed directly and in constant time. A typical illustration of random access is a volume - each folio of the book can exist open independently of others. Random access is critical to many algorithms, for example binary search.

A linked list is a sequential access data structure, where each element tin can be accesed only in particular order. A typical illustration of sequential access is a roll of paper or record - all prior material must be unrolled in order to go to data you lot want.

In this note we consider a subcase of sequential data structures, so-called limited admission information sturctures.

Stacks

A stack is a container of objects that are inserted and removed according to the last-in first-out (LIFO) principle. In the pushdown stacks only ii operations are allowed: push the particular into the stack, and popular the detail out of the stack. A stack is a express access data structure - elements tin can be added and removed from the stack simply at the top. push adds an item to the top of the stack, pop removes the item from the top. A helpful analogy is to recollect of a stack of books; you lot can remove only the summit book, too you can add a new book on the top.

A stack is a recursive data construction. Here is a structural definition of a Stack:

    a stack is either empty or
    it consistes of a tiptop and the residuum which is a stack;

Applications

  • The simplest awarding of a stack is to contrary a word. You push a given word to stack - letter by letter - and then popular letters from the stack.
  • Another application is an "undo" machinery in text editors; this functioning is achieved by keeping all text changes in a stack.
    Backtracking. This is a process when you demand to access the nearly recent data element in a serial of elements. Think of a labyrinth or maze - how do yous notice a way from an entrance to an exit?

    Once y'all attain a dead end, yous must backtrack. But backtrack to where? to the previous choice point. Therefore, at each choice betoken you store on a stack all possible choices. So backtracking just means popping a next option from the stack.

  • Language processing:
    • space for parameters and local variables is created internally using a stack.
    • compiler's syntax bank check for matching braces is implemented by using stack.
    • support for recursion

Implementation

In the standard library of classes, the data type stack is an adapter class, pregnant that a stack is built on top of other data structures. The underlying structure for a stack could be an array, a vector, an ArrayList, a linked list, or whatsoever other collection. Regardless of the type of the underlying data structure, a Stack must implement the same functionality. This is accomplished by providing a unique interface:
public interface StackInterface<AnyType> {    public void button(AnyType e);     public AnyType pop();     public AnyType peek();     public boolean isEmpty(); }        
The following pic demonstrates the idea of implementation by composition.

Another implementation requirement (in addition to the above interface) is that all stack operations must run in abiding time O(1) . Constant time means that in that location is some constant k such that an operation takes one thousand nanoseconds of computational time regardless of the stack size.

Array-based implementation

In an array-based implementation nosotros maintain the following fields: an assortment A of a default size (≥ 1), the variable top that refers to the top element in the stack and the chapters that refers to the assortment size. The variable top changes from -one to capacity - 1. We say that a stack is empty when top = -1, and the stack is full when meridian = capacity-1.

In a fixed-size stack abstraction, the capacity stays unchanged, therefore when summit reaches capacity, the stack object throws an exception. See ArrayStack.java for a complete implementation of the stack class.

In a dynamic stack abstraction when elevation reaches capacity, we double up the stack size.

Linked List-based implementation

Linked List-based implementation provides the all-time (from the efficiency point of view) dynamic stack implementation.

See ListStack.java for a consummate implementation of the stack grade.

Queues

A queue is a container of objects (a linear collection) that are inserted and removed according to the commencement-in outset-out (FIFO) principle. An first-class instance of a queue is a line of students in the food court of the UC. New additions to a line made to the back of the queue, while removal (or serving) happens in the front. In the queue merely two operations are allowed enqueue and dequeue. Enqueue means to insert an particular into the back of the queue, dequeue ways removing the front item. The picture demonstrates the FIFO admission.

The departure between stacks and queues is in removing. In a stack we remove the particular the most recently added; in a queue, we remove the particular the to the lowest degree recently added.

Implementation

In the standard library of classes, the data type queue is an adapter class, meaning that a queue is built on top of other information structures. The underlying construction for a queue could be an assortment, a Vector, an ArrayList, a LinkedList, or whatsoever other collection. Regardless of the type of the underlying information structure, a queue must implement the same functionality. This is achieved by providing a unique interface.
interface QueueInterface‹AnyType> {    public boolean isEmpty();     public AnyType getFront();     public AnyType dequeue();     public void enqueue(AnyType east);     public void articulate(); }        

Each of the above basic operations must run at constant fourth dimension O(1). The following picture show demonstrates the idea of implementation past composition.

Circular Queue

Given an array A of a default size (≥ 1) with ii references back and front, originally set to -1 and 0 respectively. Each fourth dimension nosotros insert (enqueue) a new detail, we increment the back alphabetize; when nosotros remove (dequeue) an item - we increase the front index. Here is a picture that illustrates the model later a few steps:
Equally y'all see from the motion picture, the queue logically moves in the array from left to right. Afterward several moves back reaches the finish, leaving no infinite for adding new elements

However, in that location is a costless space before the front alphabetize. We shall employ that infinite for enqueueing new items, i.east. the next entry will be stored at index 0, then i, until front end. Such a model is called a wrap effectually queue or a circular queue

Finally, when dorsum reaches forepart, the queue is total. At that place are two choices to handle a full queue:a) throw an exception; b) double the assortment size.

The circular queue implementation is done by using the modulo operator (denoted %), which is computed by taking the remainder of division (for case, 8%5 is 3). Past using the modulo operator, nosotros can view the queue equally a round array, where the "wrapped around" tin can be simulated as "back % array_size". In addition to the back and front end indexes, we maintain another index: cur - for counting the number of elements in a queue. Having this index simplifies a logic of implementation.

Run into ArrayQueue.coffee for a complete implementation of a circular queue.

Applications

The simplest two search techniques are known equally Depth-First Search(DFS) and Latitude-Showtime Search (BFS). These ii searches are described by looking at how the search tree (representing all the possible paths from the start) will be traversed.

Deapth-First Search with a Stack

In depth-first search we become down a path until we go to a dead cease; then we backtrack or back up (by popping a stack) to get an alternative path.

  • Create a stack
  • Create a new selection point
  • Push the pick point onto the stack
  • while (non institute and stack is non empty)
    • Pop the stack
    • Notice all possible choices after the terminal one tried
    • Button these choices onto the stack
  • Return

Breadth-First Search with a Queue

In breadth-starting time search we explore all the nearest possibilities by finding all possible successors and enqueue them to a queue.

  • Create a queue
  • Create a new pick bespeak
  • Enqueue the choice bespeak onto the queue
  • while (not found and queue is non empty)
    • Dequeue the queue
    • Find all possible choices afterward the last one tried
    • Enqueue these choices onto the queue
  • Return

We volition run across more than on search techniques later in the course.

Arithmetic Expression Evaluation

An important application of stacks is in parsing. For example, a compiler must parse arithmetic expressions written using infix note:
1 + ((ii + three) * 4 + 5)*6        
We intermission the problem of parsing infix expressions into two stages. Kickoff, we convert from infix to a different representation chosen postfix. And then we parse the postfix expression, which is a somewhat easier problem than directly parsing infix.

Converting from Infix to Postfix. Typically, we deal with expressions in infix notation

2 + 5        
where the operators (e.m. +, *) are written between the operands (e.q, 2 and 5). Writing the operators after the operands gives a postfix expression two and 5 are called operands, and the '+' is operator. The above arithmetic expression is called infix, since the operator is in betwixt operands. The expression
2 5 +        
Writing the operators before the operands gives a prefix expression
+2 5        
Suppose y'all want to compute the cost of your shopping trip. To do and so, y'all add a list of numbers and multiply them by the local sales tax (seven.25%):
lxx + 150 * 1.0725        
Depending on the calculator, the answer would be either 235.95 or 230.875. To avert this confusion nosotros shall use a postfix notation
seventy  150 + one.0725 *        
Postfix has the squeamish property that parentheses are unnecessary.

Now, we describe how to convert from infix to postfix.

  1. Read in the tokens one at a time
  2. If a token is an integer, write information technology into the output
  3. If a token is an operator, push information technology to the stack, if the stack is empty. If the stack is not empty, you popular entries with higher or equal priority and merely then yous button that token to the stack.
  4. If a token is a left parentheses '(', push information technology to the stack
  5. If a token is a correct parentheses ')', you pop entries until you meet '('.
  6. When you finish reading the string, you popular upward all tokens which are left there.
  7. Arithmetic precedence is in increasing social club: '+', '-', '*', '/';
Case. Suppose we accept an infix expression:2+(4+iii*2+1)/3. We read the string by characters.
'2' - send to the output. '+' - button on the stack. '(' - push on the stack. 'iv' - send to the output. '+' - push on the stack. 'three' - send to the output. '*' - push on the stack. '2' - send to the output.        

Evaluating a Postfix Expression. We describe how to parse and evaluate a postfix expression.

  1. We read the tokens in 1 at a time.
  2. If it is an integer, push information technology on the stack
  3. If it is a binary operator, popular the top 2 elements from the stack, apply the operator, and push button the event back on the stack.
Consider the following postfix expression
v nine 3 + iv 2 * * seven + *        
Here is a chain of operations
Stack Operations              Output -------------------------------------- push(v);                        5 push(9);                        5 9 push(3);                        5 9 3 push button(pop() + pop())             5 12 push(4);                        5 12 4 push(ii);                        5 12 4 2 push(popular() * pop())             five 12 viii push(pop() * popular())             five 96 push(7)                         v 96 7 button(pop() + pop())             5 103 push(pop() * pop())             515        
Note, that sectionalisation is non a commutative operation, so two/3 is non the same equally 3/2.

virgenthinficess.blogspot.com

Source: https://www.andrew.cmu.edu/course/15-121/lectures/Stacks%20and%20Queues/Stacks%20and%20Queues.html

0 Response to "what is stack and how to use it"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel