Stacks

अब Quizwiz के साथ अपने होमवर्क और परीक्षाओं को एस करें!

O(N)

If the capacity needs to be incremented to accommodate the new element, the performance of Push becomes: where N is the count

Defining Stack Operations Functionality

//Constructor Stack(); //Destructor ~Stack(); //Push Data - return if successful or not - full functionality bool Push (StackType); //Pop Data - return if successful or not - empty functionality bool Pop (StackType&);

ArrayStack will need what variables

//a constant to store the default capacity, private final int DEFAULT_CAPACITY = 10; //a variable to keep track of the top of the stack, private int count; //& a variable for the array to store the stack private T[] stack;

push

Adds an element to the top of the stack. public void push (T element){ if (count == stack.length) expandCapacity(); stack[count] = element; count++; } ■ Make sure that the array is not full. ■ Set the reference in position top of the array to the object being added to the stack. ■ Increment the values of top and count

List

An abstract data type that represents a sequence of values, where the same value may occur more than once. The name list is also used to cover several concrete data structures that can be used to implement abstract lists especially linked lists

T/F Stacks are LIFO data structures.

True.

capacity

When an array object is created, it is allocated a specific number of cells into which elements can be stored. For example, Object[] collection = Object[500];

abstract data type (ADT)

data type whose values and operations are not inherently defined w/in a programming language. It is abstract only in that the details of its implementation must be defined and should be hidden from the user. A collection, therefore, is an abstract data type.

abstraction

hides certain details at certain times. Dealing with an abstraction is easier than dealing with too many details at one time. Uses the interface and hides the details

Exceptions are said to be ________ by an operation that cannot be executed

thrown

The ______ element of the stack is the _______ ________ of the list.

top first node

Stack Implementation Array Based Top

top should always indicate the first available slot where data may be placed top will alsoindicate whether ornot the stack is empty or full

A data structure is the underlying programming constructs used to implement a collection.

true

Elements in a collection are typically organized by the order of their addition to the collection or by some inherent relationship among the elements.

true

Errors and exceptions represent unusual or invalid processing.

true

For efficiency, an array-based stack implementation keeps the bottom of the stack at index 0.

true

How we handle exceptional conditions determines whether the collection or the user of the collection controls the particular behavior.

true

Object reference variables can be used to create linked structures

true

Objects that are stored in a collection should not contain any implementation details of the underlying data structure.

true

an Object reference can be used to refer to any object

true because ultimately all classes are descendants of the Object class

generic type

we can define a class so that it stores, operates on, and manages objects whose type is not specified until the class is instantiated. For example: class Box<T>{ // declarations & code that manage objects of type T } Then, when a Box is needed, it is instantiated w a specific class used in place of T. For example, if we wanted a Box of Widget objects, we could use the following declaration: Box<Widget> box1 = new Box<Widget>; Now suppose we wanted a Box in which to store Gadget objects; we could make the following declaration: Box<Gadget> box2 = new Box<Gadget>;

We can implement a stack with a...

singly linked list

instantiate an array

stack = (T[])(new Object[DEFAULT_CAPACITY]);

A programmer should choose the structure that is appropriate for the type of data management needed.

true

A stack is the ideal data structure to use when evaluating a postfix expression.

true

back, front

Insertions to a queue occur at the ________ end and the removals occur at the ________ end

Optional operation size():

returns the number of elements in the stack

The array storing the _____ ________ may become full. A push operation will then throw a __________. Limitation of the array-based implementation. Not intrinsic to the Stack ADT.

stack elements FullStackException

Array-based Stack in C++

template <class type> class ArrayStack { private: int capacity; // stack capacity Type *S; // stack array int top; // top of stack public: ArrayStack(int c) : capacity(c) { S = new Type [capacity]; top = -1; } bool isEmpty() { return top < 0; } Type pop() throw(EmptyStackException) { if ( isEmpty() ) throw EmptyStackException("Popping from empty stack"); return S[ top-- ]; } // ... (other functions omitted)

General Stack Interface in C++

template <typename Type> class Stack { public: int size(); bool isEmpty(); Type& top() throw(EmptyStackException); void push(Type e); Type pop() throw(EmptyStackException); };

data structure

the collection of programming constructs used to implement a collection. For example, a collection might be implemented using a fixed-size structure such as an array

Type compatibility

the concept of whether a particular assignment of an object to a reference is legal

nonlinear collection

the elements are organized in something other than a straight line, such as a hierarchy or a network. For that matter, a nonlinear collection may not have any organization at all.

linear collection

the elements of the collection are organized in a straight line

top

the end to which elements are added and from which they are removed

Amortized Analysis (aka Aggregate Analysis)

the idea is the worst case operation can alter the state in such a way that the worst case cannot occur again for a "long" time

nodes

the objects stored in a linked list are referred to generically as the nodes of the list

an ArrayList can be used to store any kind of object

true

stack

(LIFO) a linear collection whose elements are added & removed from the same end. We say that a stack is processed in a last in, first out manner. The last element to be put on a stack will be the first one that gets removed.

Dynamic (growable) Array-based Stack: In a push operation, when the array is full, instead of throwing an exception, we can replace the array with a larger one. How large should the new array be?

-incremental strategy: increase the size by a constant c -doubling strategy: double the size

When a function is called, the run-time system pushes on the stack a frame containing...

-local variables and return value -program counter, keeping track of the statement being executed

solve this postfix expression 3 4 * 2 5 4 * 2

12 2 5 4 * 2 then 12 7 4 * 2 then 5 4 * 2 then 20 2 then 10

priority queue

A data structure that is first in first out but allows things to "cut" in line is called a __________

Stack

A data structure that stores information in a Last In First out manner is called a ______

Record

A data structure which consists of a collection of elements, typically in fixed number and sequence and typically indexed by names. The elements of records may also be called fields

Queue

A dynamic data structure of the form First In First Out (FIFO)

Stack

A dynamic data structure of the form Last In First Out (LIFO)

Linked List

A list where each item contains the data together with a pointer to the next item. There may be an additional pointer to the previous item. This means the items can be accessed in order even if they are not stored in order; they do not have to be stored in adjacent memory locations

Describe an application where a queue would be most appropriate and explain why it is the most appropriate data structure.

A printer queue. The way data is stored with a queue (FIFO) makes it ideal as this is equally the same order required with a printer queue (the first print job added will be the first job complete).

Array

A set of data items of the same type grouped together using a single identifier. Each of the data items is addressed by the variable name and a subscript

Describe an application where a stack would be most appropriate and explain why it is the most appropriate data structure.

An undo function for a word processor. The way data is stored in a stack (FILA) makes it ideal as words are written in a similar manner and a stack can easily point to and return earlier values and delete most recent values.

Tuple

Another name for a record

Give a list of commands to describe inserting a new data item into a stack.

Check to see if stack is full. If the stack is full report an error and stop. Increment the stack pointer. Insert new data item into cell pointed by the stack pointer and stop.

Give a list of commands to describe deleting a data item in a stack.

Check to see if the stack is empty. If the stack is empty report an error and stop. Delete data item in cell pointed to by the stack pointer. Lower the stack pointer.

isEmpty

Determines if the stack is empty.

size

Determines the number of elements on the stack.

Using a _________ array to implement a stack meets the ADT specification requirements for a stack. Doing so does NOT limit the stack size.

Dynamic

Attempting to execute pop or top on an empty stack throws a(n)....

EmptyStackException

peek

Examines the element at the top of the stack.

Give characteristics of a queue.

Example of a FIFO data structure. Works similar to a supermarket queue. Nodes are removed only from the head. Nodes are added only from the tail.

Give a difference between a stack and queue.

In a stack the most recent items added are the first to be removed. In a queue the most recent items added are the last to be removed.

Items in a stack must be removed in the reverse order that they were added to the stack. This is referred to as a...

Last In, First Out structure

Stack is what kind of data structure?

Last in, first out (LIFO)

The space used is _____ and each operation of the Stack ADT takes ____ time operations: push, pop, top, size, empty

O(n) O(1)

O(1)

Performance of Pushing and Popping

What is the advantage of postfix notation?

Postfix notation avoids the need for precedence rules that are required to evaluate infix expressions

Give an example of a FIFO data structure

Queue

pop

Removes an element from the top of the stack. ■ Make sure the stack is not empty. ■ Decrement the top counter. ■ Set a temporary reference equal to the element in stack[top]. ■ Set stack[top] equal to null. ■ Return the temporary reference.

What are the advantages of the java.util.Stack implementation of a stack?

Since the java.util.Stack implementation is an extension of the Vector class, it can keep track of the positions of elements in the stack using an index and thus does not require each node to store an additional pointer. This implementation also allocates space only as it is needed, like the linked implementation.

meaningless

Sorting and searching are _________ in regard to stacks

Give an example of a FILO data structure

Stack

Formula for the amortized cost

T(n) / n

internal array

The Stack<t> is implemented using a(n) _________ _________

peek

The _____ method allows one to look at the item on top of a stack or a queue without modifying it

Queue

The _______ is a data structure that operates on a first in first out basis

activation frame

The collection of information that must be saved in order to return a method to its state when the execution was transferred to the called method is called a(n) __________ __________

What is the potential problem with the java.util.Stack implementation?

The java.util.Stack implementation is an extension of the Vector class and thus inherits a large number of operations that violate the basic assumptions of a stack.

Stack

a Last in, First Out data structure. So like a stack of plates, items are added to the top and removed.

linked structure

a data structure that uses object reference variables to create links between objects. Linked structures are the primary alternative to an array-based implementation of a collection.

data type

a group of values & the operations defined on those values

Array-based implementation of stack ADT Limitations: -The maximum size of the stack must be defined __ ________, and cannot be changed. -Trying to push a new element onto a full stack causes an _________ ________ ________

a priori implementation-specific exception

Linked lists:

allow dynamic element addition

The process of decreasing an amount over time

amortization

pointer

an object reference variable holds the address of an object, indicating where the object is stored in memory. The following declaration creates a variable called obj that is only large enough to hold the numeric address of an object: Object obj;

APIs

application programming interfaces

Stacks store...

arbitrary objects think Pez dispensers pancakes plates trays

A simple way of implementing the Stack ADT uses a(n)___________ We add elements from left to right A ________ keeps track of the index of the top element

array variable

Stack can be implemented as...

array or linked list

primitive data types

byte short int long float double char

What if the stack is empty on a pop?

catch (EmptyCollectionException exception)

The C++ run-time system keeps track of the...

chain of active functions with a stack

When a function returns, its frame is popped from the stack and...

control is passed back to the function that called it

stack interface

defined as Stack<T>, operating on a generic type T

Attempting to execute an operation of ADT may cause an error condition called a(n)...

exception

How an Abstract Data Type is implemented...

greatly affects how well algorithms will perform

Stack operation top():

returns a reference to the top element of the stack, but doesn't remove it

Reuse

in its purest form, should mean that we create a collection that is written once, compiled into byte code once, and will then handle any objects we choose to store in it safely, efficiently, and effectively

Stack operation push(e):

inserts an element to the top of the stack

type check this code- String x = new Integer(10);

it is not legal since you cannot assign a reference declared to be of type String to point to an object of type Integer

Arrays:

limited number of elements

Static Array and Array-based implementation of Stack ADT Performance: -Let ___ be the number of elements in the stack -The space used is ____ -Each operation (push, pop, top, size, empty) runs in time ____

n O(n) O(1)

In the Stack ADT, ____ and _____ cannot be performed if the stack is empty

pop top

stack expandCapacity()

private void expandCapacity() { T[] larger = (T[])(new Object[stack.length*2]); for (int index=0; index < stack.length; index++) larger[index] = stack[index]; stack = larger; } The expandCapacity method is implemented to double the size of the array as needed. Of course since an array cannot be resized once it is instantiated, this method simply creates a new larger array, and then copies the contents of the old array into the new one. It serves as a support method of the class and can therefore be implemented with private visibility.

Standard Template Library (STL)

provides a class to implement a stack in a program

stack toString

public String toString(){ String result = "<top of stack>\n"; for (int index=count-1; index >= 0; index—) result += stack[index] + "\n"; return result + "<bottom of stack>"; }

self-referential

public class Person { private String name; private String address; private Person next; // a link to another Person object } Using only this one class, a linked structure can be created. One Person object contains a link to a second Person object. This second object also contains a reference to a Person, which contains another, and so on. This kind of relationship forms the basis of a linked list, which is a linked structure in which one object refers to the next, creating a linear ordering of the objects in the list.

Stack operation pop():

removes and returns the top element of the stack

Optional operation empty():

returns a bool indicating if the stack contains any objects

a linked list has no upper bound on its capacity other than the limitations of memory in the computer.

true

Convert FPE Infix: ( ( (x + y) * z) - (a + b) ) to Postfix:

x y +z * a b + -

What is the characteristic behavior of a stack?

A stack is a last in, first out (LIFO) structure.

Convert FPE Infix: ( (A + B) * (C - E) ) / (F + G) ) to Postfix:

AB+CE-*FG+/

What is abstraction and what advantage does it provide?

Abstraction is the concept of hiding the underlying implementation of operations and data storage in order to simplify the use of a collection.

What is an abstract data type?

An abstract data type is a data type that is not defined within the programming language and must be defined by the programmer.

What are the advantages to using an array implementation as opposed to a linked implementation?

An array implementation uses less space per object since it only has to store the object and not an extra pointer. However, the array implementation will allocate much more space than it needs initially.

Defining Stack Data Array Based

An array of some set size - this is where the stack data is kept. An integer field to be used to mark the top.

How do object references help us define data structures?

An object reference can be used as a link from one object to another. A group of linked objects can form a data structure, such as a linked list, on which a collection can be based.

Why should a linked list node be separate from the element stored on the list?

It is unreasonable to assume that every object that we may want to put in a collection can be designed to cooperate with the collection implementation. Furthermore, the implementation details are supposed to be kept distinct from the user of the collection, including the elements the user chooses to add to the collection.

Stack Implementation POPping a Linked List

Data = top; top = top->next; delete Data;

DFS

Depth First Search (backtracking) - discover path from start to goal by visiting neighbors and retreating to find unvisited neighbors

Stack Application Reverse Polish Notation (notation will)

Eliminate precedence (thus allowing a left to right evaluation) Eliminate parenthesis

What impact would the use of sentinel nodes or dummy nodes have upon a doubly linked list implementation?

It would take two dummy records in a doubly linked list, one at the front and one at the rear, to eliminate the special cases when dealing with the first and last node.

Pop

Method which will remove the data found at the top of the stack and will send it to the application. The top of the stack will be changed to the next element in the stack.

Push

Method which will store data sent from the application onto the stack. Where this data is placed now becomes the top and of the stack.

Given the example in figure 14.4, will the following code compile? Horse creature = new Mammal();

No, a reference variable for a child or subclass may not hold a reference to a parent or superclass. To make this assignment, you would have to explicitly cast the parent class into the child class (Horse creature = (Horse)(new Mammal());

Underflow

Occurs when the stack pointer is -1 (Stack is empty) if the user attempts to pop an item from the stack.

Overflow

Occurs when the stack pointer is at the max size and the user attempts to push an item onto the list. Can be prevented by sending an error message to the user.

Stack Implementation Linked List Based

Only data needed is a pointer to the top of the linked list. Very efficient, you are always pushing and popping from the top. There is no list traversal!! An empty condition is when top = NULL. A full condition is when you cannot obtain dynamic memory.

Stack Implementation PUSHing a Linked List

P = new Node; P->next = top; top = P;

Define inheritance?

Inheritance is the process in which a new class is derived from an existing one. The new class automatically contains some or all of the variables and methods in the original class. Then, to tailor the class as needed, the programmer can add new variables and methods to the derived class, or modify the inherited ones.

Stack Application Reverse Polish Notation Evaluation (Steps)

Scan expression left to right If token is an operand then push If token is an operator then pop two, evaluate and push result If the postfix expression was correctly formed then when all tokens have been processed there should be one element remaining on the stack; this should be the answer.

What special case exists when managing linked lists?

The primary special case in linked list processing occurs when dealing with the first element in the list. A special reference variable is maintained that specifies the first element in the list. If that element is deleted, or a new element is added in front of it, the front reference must be carefully maintained

Convert FPE Infix: (c * (a - b) ) to Postfix:

c a b - *

collection

is an object that gathers and organizes other objects

LIFO

last in, first out

What are some of the other operations that might be implemented for a stack?

makeEmpty(), destroy(), full()

Infix to Postfix expression (2 rules)

1) operand order does not change 2) operators are in order of evaluation

RRRRobust Stack: Empty

Before pop can function, you must assure there is data to be popped. This can be implemented as a separate method or incorporated into the pop function.

What is the advantage of postfix notation?

Postfix notation avoids the need for precedence rules that are required to evaluate infix expressions

Stack Application Reverse Polish Notation Evaluation

Requires the usage of an operand stack A postfix expression consists of two types of tokens; operators and operands.

Palindrome (Something to note)

Spaces matter in definition. Some definitions will strip spaces and just take the raw text.

Palindrome Problem

Step by Step 1.Instantiate two stacks, S1 and S2 2.Push string into S1 3.POP half of S1 onto S2 4.If length of string is odd, an extra character will be in S1 5.POP S1 and S2 and compare popped values 6.If values are equal go back to step 5 assuming S1 and S2 are not enpty 7.output if the string is or is not a palindrome.

Given the example in Figure 14.4, list the subclasses of Mammal?

The subclasses of Mammal are Horse and Bat.

push(item)

adds a new item to the top of the stack.

stack.push(object)

adds object to top of stack

isEmpty()

test to see whether the stack is empty, and returns a boolean value

IsFull()

test to see whether the stack is full, and returns a boolean value

A Java interface defines a set of abstract methods and is useful in separating the concept of an abstract data type from its implementation

true

A linked list dynamically grows as needed and essentially has no capacity limitations.

true

A linked list is composed of objects that each point to the next object in the list.

true

A polymorphic reference uses the type of the object, not the type of the reference, to determine which version of a method to invoke.

true

Any implementation of a collection can be used to solve a problem as long as it validly implements the appropriate operations.

true

For efficiency, an array-based stack implementation keeps the bottom of the stack at index 0.

true

Stack Application Reverse Polish Notation Infix to Postfix Practice

2 + 3 * 4 Answer: 2 3 4 * + 2) A + (B - D) * E - F Answer: A B D - E * + F-

Stack Application Reverse Polish Notation Examples Infix

3 + 2 3 + 2 * 4 3 + 2 * 4 - (5 + 2)

Stack Application Reverse Polish Notation Examples Postfix

3 2 + 3 2 4 * + 3 2 4 * + 5 2 + -

Stack Application Reverse Polish Notation Evaluation Practice

3 4 5 + - Answer: -6 6 1 - 3 * 5 7 8 / + + Answer: 18 2 6 + 5 * - Answer: invalid expression

What is a stack?

A LIFO (last in, first out) structure. Access (storage or retrieval) may only take place at the Top of the stack. No random access to other elements within the stack.

Stack Implementation Array Based

A Stack object will contain: An array of StackTypes: Data An integer control field: Top

What is a collection?

A collection is an object that gathers and organizes other objects

What is a data structure?

A data structure is the set of objects necessary to implement an abstract data type.

What is a data type?

A data type is a set of values and operations on those values defined within a programming language.

What are the advantages to using a linked implementation as opposed to an array implementation?

A linked implementation allocates space only as it is needed & has a theoretical limit of the size of the hardware.

Compare and contrast a linked list and an array.

A linked list has no capacity limitations, while an array does. However, arrays provide direct access to elements using indexes, whereas a linked list must be traversed one element at a time to reach a particular point in the list.

Defining Stack Data Linked List Based

A pointer whichcontains theaddress for the top node in the stack.

What is the difference between a doubly linked list and a singly linked list?

A singly linked list maintains a reference to the first element in the list and then a next reference from each node to the following node in the list. A doubly linked list maintains two references: front and rear. Each node in the doubly linked list stores both a next and a previous reference

Stack Implementation

Contains: Data, Top An array of StackTypes: Data An I Teheran Co trolley field: Top Top should always indicate the first available data may be placed. Top will also indicate whether or not the stack is empty or full.

Stack Application Reverse Polish Notation

Arithmetic expressions are normally written in infix notation. It is called infix because the arithmetic operator (i.e. +, -, *, /) is in-between the operands. Example: 5 + 3 * 2 - 6 The answer above is 5. It is difficult to develop an algorithm to evaluate infix expressions due to precedence problems. You cannot simply evaluate an expression straight left to right! Part of the task of a compiler is to generate machine language instructions to carry out the evaluation of an arithmetic expression. Ex. Z = a + b * c - d; If we could evaluate an arithmetic expression by simply going straight left to right, the task of the compiler would be much easier.

RRRRobust Stack: Full

Before push can function, you must assure there is room for the data to be pushed. This can be implemented as a separate method or incorporated into the push function.

What is the purpose of Generics in the Java language?

Beginning with Java 5.0, Java enables us to define a class based on a generic type. That is, we can define a class so that it stores, operates on, and manages objects whose type is not specified until the class is instantiated. This allows for the creation of structures that can manipulate "generic" elements and still provide type checking

What do the LinkedStack<T> and ArrayStack<T> classes have in common?

Both the LinkedStack<T> and ArrayStack<T> classes implement the StackADT<T> interface. This means that they both represent a stack collection, providing the necessary operations needed to use a stack. Though they both have distinct approaches to managing the collection, they are functionally interchangeable from the user's point of view

Why is a class an excellent representation of an abstract data type?

Classes naturally provide abstraction since only those methods that provide services to other classes have public visibility.

T/F Removal from a stack only occurs from the bottom in reverse order from which they were inserted.

False. Removed from top in reverse order from insertion.

FPE

Fully Parenthesized Expression - exactly one set of parentheses enclosing each operator and its operands

Stack Application Reverse Polish Notation Infix to Postfix Conversion (Steps)

If token is an operand, push onto postfix string. If token is an operator, compare this with the top of the operator stack If token is lesser (precedence), pop the operator stack and push onto postfix string then revaluate If token is greater(precedence), push onto the operator stack If token is equal (precedence) use the lesser rule Comparing against an empty operator stack will always result in a push onto the operator stack If token is left (, there is an automatic push. Also Precedence level of left (, is the lowest if token is right), pop everything from the stack untill you get to the matching left )

Palindrome

Text which if written backwards would be the exact same text 1234321 BOB ABLE WAS I ERE I SAW ELBA

Define polymorphism?

The term polymorphism can be defined as "having many forms." A polymorphic reference is a reference variable that can refer to different types of objects at different points in time. The specific method invoked through a polymorphic reference can change from one invocation to the next

What would be the time complexity of the push operation if we chose to push at the end of the list instead of the front?

To push at the end of the list, we would have to traverse the list to reach the last element. This traversal would cause the time complexity to be O(n). An alternative would be to modify the solution to add a rear reference that always pointed to the last element in the list. This would help the time complexity for add but would have consequences if we try to remove the last element.

Palindrome (the problem)

Write a function which will take a string on input and will output if this string is or is not a palindrome. The solution must utilize a stack ADT when executing the solution.

Given the example in figure 14.4, will the following code compile? Animal creature = new Parrot();

Yes, a reference variable of a parent class or any superclass may hold a reference to one of its descendants.

What are the five basic operations on a stack?

push—adds an element to the end of the stack pop—removes an element from the front of the stack peek—returns a reference to the element at the front of the stack isEmpty—returns true if the stack is empty, returns false otherwise size—returns the number of elements in the stack

pop()

removes and returns the top item from the stack.

stack.top( )

returns object at top of stack, does not remove - also called peek( )

peek()

returns the top item from the stack but does not remove it.

stack.empty( )

returns true if nothing in stack

A collection is an abstraction where the details of the implementation are hidden.

true

A linked implementation of a stack adds and removes elements from one end of the linked list.

true

By using the interface name as a return type, the interface doesn't commit the method to the use of any particular class that implements a stack.

true

Dealing with the first node in a linked list often requires special handling.

true

Implementing a list with a sentinel node or dummy node as the first node eliminates the special cases dealing with the first node.

true

Stack elements are processed in a LIFO manner—the last element in is the first element out.

true

The implementation of the collection operations should not affect the way users interact with the collection.

true

The java.util.Stack class is derived from Vector, which gives a stack inappropriate operations

true

The order in which references are changed is crucial to maintaining a linked list.

true


संबंधित स्टडी सेट्स

Values, Ethics, and Advocacy - Chapter 5 - Module

View Set

Chem chapter 16 blackboard review

View Set

Practice Questions 3.1 Sensation

View Set

Marketing Management Chapter 10 and 11

View Set

Ch. 41 Drugs for Bowel Disorders and GI Conditions

View Set

Which bone articulates with what?

View Set