61
Lists, Stacks, and Queues (Lists, Stacks, and Queues ) Data Structures Fall 2019 1 / 61

Lists, Stacks, and Queuesccf.ee.ntu.edu.tw/~yen/courses/ds19F/chapter-3.pdf · (Lists, Stacks, and Queues ) Data Structures Fall 2019 26 / 61. Linked Lists A linked list is a series

  • Upload
    others

  • View
    2

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Lists, Stacks, and Queuesccf.ee.ntu.edu.tw/~yen/courses/ds19F/chapter-3.pdf · (Lists, Stacks, and Queues ) Data Structures Fall 2019 26 / 61. Linked Lists A linked list is a series

Lists, Stacks, and Queues

(Lists, Stacks, and Queues ) Data Structures Fall 2019 1 / 61

Page 2: Lists, Stacks, and Queuesccf.ee.ntu.edu.tw/~yen/courses/ds19F/chapter-3.pdf · (Lists, Stacks, and Queues ) Data Structures Fall 2019 26 / 61. Linked Lists A linked list is a series

Abstract Data Types (ADT)

Data typeI a set of objects + a set of operationsI Example: integer

F set of integer numbersF operations: +, -, x, /

Can this be generalized? e.g. procedures generalize the notion ofan operatorAbstract data type

I what can be stored in the ADTI what operations can be done on/by the ADT

EncapsulationI Operations on ADT can only be done by calling appropriate

functionsI no mention of how the set of operations is implementedI ADT→ C++: classI method→ C++: member function

(Lists, Stacks, and Queues ) Data Structures Fall 2019 2 / 61

Page 3: Lists, Stacks, and Queuesccf.ee.ntu.edu.tw/~yen/courses/ds19F/chapter-3.pdf · (Lists, Stacks, and Queues ) Data Structures Fall 2019 26 / 61. Linked Lists A linked list is a series

Abstract Data Types (Cont’d)

(Lists, Stacks, and Queues ) Data Structures Fall 2019 3 / 61

Page 4: Lists, Stacks, and Queuesccf.ee.ntu.edu.tw/~yen/courses/ds19F/chapter-3.pdf · (Lists, Stacks, and Queues ) Data Structures Fall 2019 26 / 61. Linked Lists A linked list is a series

Address vs. Value

Sometimes we want to deal with the address of a memorylocation, rather than the value it contains.R2 is a pointer – it contains the address of data we are interestedin.

(Lists, Stacks, and Queues ) Data Structures Fall 2019 4 / 61

Page 5: Lists, Stacks, and Queuesccf.ee.ntu.edu.tw/~yen/courses/ds19F/chapter-3.pdf · (Lists, Stacks, and Queues ) Data Structures Fall 2019 26 / 61. Linked Lists A linked list is a series

Arrays vs. Pointers

PointerI Address of a variable in memoryI Allows us to indirectly access variables

F in other words, we can talk about its address rather than its value

ArrayI A list of values arranged sequentially in memoryI Example: a list of telephone numbersI Expression a[4] refers to the 5th element of the array a

(Lists, Stacks, and Queues ) Data Structures Fall 2019 5 / 61

Page 6: Lists, Stacks, and Queuesccf.ee.ntu.edu.tw/~yen/courses/ds19F/chapter-3.pdf · (Lists, Stacks, and Queues ) Data Structures Fall 2019 26 / 61. Linked Lists A linked list is a series

Arrays in C

(Lists, Stacks, and Queues ) Data Structures Fall 2019 6 / 61

Page 7: Lists, Stacks, and Queuesccf.ee.ntu.edu.tw/~yen/courses/ds19F/chapter-3.pdf · (Lists, Stacks, and Queues ) Data Structures Fall 2019 26 / 61. Linked Lists A linked list is a series

Array Syntax

(Lists, Stacks, and Queues ) Data Structures Fall 2019 7 / 61

Page 8: Lists, Stacks, and Queuesccf.ee.ntu.edu.tw/~yen/courses/ds19F/chapter-3.pdf · (Lists, Stacks, and Queues ) Data Structures Fall 2019 26 / 61. Linked Lists A linked list is a series

Pointers in C

Declarationint *p; /* p is a pointer to an int */

I A pointer in C is always a pointer to a particular data type:int*, double*, char*, etc.

OperatorsI ∗p – returns the value pointed to by pI &z – returns the address of variable z

(Lists, Stacks, and Queues ) Data Structures Fall 2019 8 / 61

Page 9: Lists, Stacks, and Queuesccf.ee.ntu.edu.tw/~yen/courses/ds19F/chapter-3.pdf · (Lists, Stacks, and Queues ) Data Structures Fall 2019 26 / 61. Linked Lists A linked list is a series

Example

(Lists, Stacks, and Queues ) Data Structures Fall 2019 9 / 61

Page 10: Lists, Stacks, and Queuesccf.ee.ntu.edu.tw/~yen/courses/ds19F/chapter-3.pdf · (Lists, Stacks, and Queues ) Data Structures Fall 2019 26 / 61. Linked Lists A linked list is a series

Syntax for Pointer Operators

Declaring a pointerI type *var;I type* var;- Either of these work – whitespace doesn’t matter.

Type of variable is int* (integer pointer), char* (char pointer), etc.Creating a pointer

I &var- Must be applied to a memory object, such as a variable.

In other words, &3 is not allowed.

DereferencingCan be applied to any expression. All of these are legal:

I *var – contents of mem loc pointed to by varI **var – contents of mem loc pointed to by memory location pointed

to by varI *3 contents of memory location 3

(Lists, Stacks, and Queues ) Data Structures Fall 2019 10 / 61

Page 11: Lists, Stacks, and Queuesccf.ee.ntu.edu.tw/~yen/courses/ds19F/chapter-3.pdf · (Lists, Stacks, and Queues ) Data Structures Fall 2019 26 / 61. Linked Lists A linked list is a series

Arrays and Pointers

An array name is essentially a pointer to the first element in thearray

I char word[10];I char *cptr;I cptr = word; /* points to word[0] */

Each line below gives three equivalent expressions:

(Lists, Stacks, and Queues ) Data Structures Fall 2019 11 / 61

Page 12: Lists, Stacks, and Queuesccf.ee.ntu.edu.tw/~yen/courses/ds19F/chapter-3.pdf · (Lists, Stacks, and Queues ) Data Structures Fall 2019 26 / 61. Linked Lists A linked list is a series

What is recursion and why use recursion?

A technique that solves problem by solving smaller versions ofthe same problem!When you turn this into a program, you end up with functionsthat call themselves (i.e., recursive functions)Recursive algorithms can simplify the solution of a problem, oftenresulting in shorter, more easily understood source code.But ... they often less efficient, both in terms of time and space,than non-recursive (e.g., iterative) solutions.

(Lists, Stacks, and Queues ) Data Structures Fall 2019 12 / 61

Page 13: Lists, Stacks, and Queuesccf.ee.ntu.edu.tw/~yen/courses/ds19F/chapter-3.pdf · (Lists, Stacks, and Queues ) Data Structures Fall 2019 26 / 61. Linked Lists A linked list is a series

Recursion vs. Iteration

IterationI Uses repetition structures (for, while or do ... while)I Repetition through explicitly use of repetition structure.I Terminates when loop-continuation condition fails.I Controls repetition by using a counter.

RecursionI Uses selection structures (if, if ... else or switch)I Repetition through repeated function calls.I Terminates when base case is satisfied.I Controls repetition by dividing problem into simpler one(s).

(Lists, Stacks, and Queues ) Data Structures Fall 2019 13 / 61

Page 14: Lists, Stacks, and Queuesccf.ee.ntu.edu.tw/~yen/courses/ds19F/chapter-3.pdf · (Lists, Stacks, and Queues ) Data Structures Fall 2019 26 / 61. Linked Lists A linked list is a series

General Form of Recursive Functions

(Lists, Stacks, and Queues ) Data Structures Fall 2019 14 / 61

Page 15: Lists, Stacks, and Queuesccf.ee.ntu.edu.tw/~yen/courses/ds19F/chapter-3.pdf · (Lists, Stacks, and Queues ) Data Structures Fall 2019 26 / 61. Linked Lists A linked list is a series

n! (n factorial)

There are many problems whose solution can be defined recursively

(Lists, Stacks, and Queues ) Data Structures Fall 2019 15 / 61

Page 16: Lists, Stacks, and Queuesccf.ee.ntu.edu.tw/~yen/courses/ds19F/chapter-3.pdf · (Lists, Stacks, and Queues ) Data Structures Fall 2019 26 / 61. Linked Lists A linked list is a series

Coding the factorial function

Recursive implementationint Factorial (int n)if (n==0) // base case

return 1;else

return n * Factorial(n-1); // decompose, solve, combine

(Lists, Stacks, and Queues ) Data Structures Fall 2019 16 / 61

Page 17: Lists, Stacks, and Queuesccf.ee.ntu.edu.tw/~yen/courses/ds19F/chapter-3.pdf · (Lists, Stacks, and Queues ) Data Structures Fall 2019 26 / 61. Linked Lists A linked list is a series

How does the computer Implement recursion?

It uses a stack called ”run-time” stack to keep track of the functioncalls.Each time a function is called recursively, an ”activation record” iscreated and stored in the stack.When recursion returns, the corresponding activation is poppedout of the stack.

(Lists, Stacks, and Queues ) Data Structures Fall 2019 17 / 61

Page 18: Lists, Stacks, and Queuesccf.ee.ntu.edu.tw/~yen/courses/ds19F/chapter-3.pdf · (Lists, Stacks, and Queues ) Data Structures Fall 2019 26 / 61. Linked Lists A linked list is a series

What happens during a function call?

(Lists, Stacks, and Queues ) Data Structures Fall 2019 18 / 61

Page 19: Lists, Stacks, and Queuesccf.ee.ntu.edu.tw/~yen/courses/ds19F/chapter-3.pdf · (Lists, Stacks, and Queues ) Data Structures Fall 2019 26 / 61. Linked Lists A linked list is a series

What happens during a function call?

An activation record is stored into the run-time stack:I The system stops executing function b and starts executing

function aI Since it needs to come back to function b later, it needs to store

everything about function b that is going to need (x, y, z, and theplace to start executing upon return)

I Then, x from a is bounded to w from bI Control is transferred to function a

After function a is executed, the activation record is popped out ofthe run-time stack

I All the old values of the parameters and variables in function b arerestored and the return value of function a replaces a(x) in theassignment statement

(Lists, Stacks, and Queues ) Data Structures Fall 2019 19 / 61

Page 20: Lists, Stacks, and Queuesccf.ee.ntu.edu.tw/~yen/courses/ds19F/chapter-3.pdf · (Lists, Stacks, and Queues ) Data Structures Fall 2019 26 / 61. Linked Lists A linked list is a series

Recursive Function Calls

There is no difference between recursive and non-recursive calls!

int f(int x)int y;if(x==0)return 1;elsey = 2 * f(x-1);return y+1;

(Lists, Stacks, and Queues ) Data Structures Fall 2019 20 / 61

Page 21: Lists, Stacks, and Queuesccf.ee.ntu.edu.tw/~yen/courses/ds19F/chapter-3.pdf · (Lists, Stacks, and Queues ) Data Structures Fall 2019 26 / 61. Linked Lists A linked list is a series

Computing f (3)

(Lists, Stacks, and Queues ) Data Structures Fall 2019 21 / 61

Page 22: Lists, Stacks, and Queuesccf.ee.ntu.edu.tw/~yen/courses/ds19F/chapter-3.pdf · (Lists, Stacks, and Queues ) Data Structures Fall 2019 26 / 61. Linked Lists A linked list is a series

The List ADT

A sequence of zero or more elements:

A1,A2,A3, · · · ,AN

N: length of the listA1: first elementAN: last elementIf N = 0, then empty list

I Ai precedes Ai+1I Ai follows Ai−1

(Lists, Stacks, and Queues ) Data Structures Fall 2019 22 / 61

Page 23: Lists, Stacks, and Queuesccf.ee.ntu.edu.tw/~yen/courses/ds19F/chapter-3.pdf · (Lists, Stacks, and Queues ) Data Structures Fall 2019 26 / 61. Linked Lists A linked list is a series

List Operations

printList: print the listmakeEmpty: create an empty listfind: locate the position of an object in a list

I list: 34,12, 52, 16, 12I find(52)→ 3

insert: insert an object to a listI insert(x,3)→ 34, 12, 52, x, 16, 12

remove: delete an element from the listI remove(52)→ 34, 12, x, 16, 12

findKth: retrieve the element at a certain position

(Lists, Stacks, and Queues ) Data Structures Fall 2019 23 / 61

Page 24: Lists, Stacks, and Queuesccf.ee.ntu.edu.tw/~yen/courses/ds19F/chapter-3.pdf · (Lists, Stacks, and Queues ) Data Structures Fall 2019 26 / 61. Linked Lists A linked list is a series

Implementation of an ADT

Choose a data structure to represent the ADT. E.g. arrays, records,etc.Each operation associated with the ADT is implemented by one ormore subroutinesTwo standard implementations for the list ADT

I Array-basedI Linked list

(Lists, Stacks, and Queues ) Data Structures Fall 2019 24 / 61

Page 25: Lists, Stacks, and Queuesccf.ee.ntu.edu.tw/~yen/courses/ds19F/chapter-3.pdf · (Lists, Stacks, and Queues ) Data Structures Fall 2019 26 / 61. Linked Lists A linked list is a series

Array Implementation

Requires an estimate of the maximum size of the list – waste spaceprintList and find: linearfindKth: constantinsert and delete: slow

I e.g. insert at position 0 (making a new element) requires firstpushing the entire array down one spot to make room

I e.g. delete at position 0 requires shifting all the elements in the listup one

I On average, half of the lists needs to be moved for either operation

(Lists, Stacks, and Queues ) Data Structures Fall 2019 25 / 61

Page 26: Lists, Stacks, and Queuesccf.ee.ntu.edu.tw/~yen/courses/ds19F/chapter-3.pdf · (Lists, Stacks, and Queues ) Data Structures Fall 2019 26 / 61. Linked Lists A linked list is a series

Pointer Implementation (Linked List)

The list is not stored contiguouslyA series of structures that are not necessarily adjacentEach node contains the element and a pointer to a structurecontaining its successor; the last cells next link points to NULLCompared to the array implementation,

I√

the pointer implementation uses only as much space as is neededfor the elements currently on the list

I × but requires space for the pointers in each cell

(Lists, Stacks, and Queues ) Data Structures Fall 2019 26 / 61

Page 27: Lists, Stacks, and Queuesccf.ee.ntu.edu.tw/~yen/courses/ds19F/chapter-3.pdf · (Lists, Stacks, and Queues ) Data Structures Fall 2019 26 / 61. Linked Lists A linked list is a series

Linked Lists

A linked list is a series of connected nodesEach node contains at least

I A piece of data (any type)I Pointer to the next node in the list

Head: pointer to the first nodeThe last node points to NULL

(Lists, Stacks, and Queues ) Data Structures Fall 2019 27 / 61

Page 28: Lists, Stacks, and Queuesccf.ee.ntu.edu.tw/~yen/courses/ds19F/chapter-3.pdf · (Lists, Stacks, and Queues ) Data Structures Fall 2019 26 / 61. Linked Lists A linked list is a series

A Simple Linked List Class

Declare Node class for the nodes

Declare List, which containsI head: a pointer to the first node in the list.I Since the list is empty initially, head is set to NULL Operations on

List

(Lists, Stacks, and Queues ) Data Structures Fall 2019 28 / 61

Page 29: Lists, Stacks, and Queuesccf.ee.ntu.edu.tw/~yen/courses/ds19F/chapter-3.pdf · (Lists, Stacks, and Queues ) Data Structures Fall 2019 26 / 61. Linked Lists A linked list is a series

Inserting a New Node

Node* InsertNode(int index, double x)I Insert a node with data equal to x after the index’th elements.

(i.e., when index = 0, insert the node as the first element; whenindex = 1, insert the node after the first element, and so on)

I If the insertion is successful, return the inserted node. Otherwise,return NULL.(If index is < 0 or > length of the list, the insertion will fail.)

StepsI Locate index’th elementI Allocate memory for the new nodeI Point the new node to its successorI Point the new nodes predecessor to the new node

(Lists, Stacks, and Queues ) Data Structures Fall 2019 29 / 61

Page 30: Lists, Stacks, and Queuesccf.ee.ntu.edu.tw/~yen/courses/ds19F/chapter-3.pdf · (Lists, Stacks, and Queues ) Data Structures Fall 2019 26 / 61. Linked Lists A linked list is a series

Inserting a New Node (Cont’d)

(Lists, Stacks, and Queues ) Data Structures Fall 2019 30 / 61

Page 31: Lists, Stacks, and Queuesccf.ee.ntu.edu.tw/~yen/courses/ds19F/chapter-3.pdf · (Lists, Stacks, and Queues ) Data Structures Fall 2019 26 / 61. Linked Lists A linked list is a series

Inserting a New Node (Cont’d)

(Lists, Stacks, and Queues ) Data Structures Fall 2019 31 / 61

Page 32: Lists, Stacks, and Queuesccf.ee.ntu.edu.tw/~yen/courses/ds19F/chapter-3.pdf · (Lists, Stacks, and Queues ) Data Structures Fall 2019 26 / 61. Linked Lists A linked list is a series

Inserting a New Node (Cont’d)

(Lists, Stacks, and Queues ) Data Structures Fall 2019 32 / 61

Page 33: Lists, Stacks, and Queuesccf.ee.ntu.edu.tw/~yen/courses/ds19F/chapter-3.pdf · (Lists, Stacks, and Queues ) Data Structures Fall 2019 26 / 61. Linked Lists A linked list is a series

Inserting a New Node (Cont’d)

(Lists, Stacks, and Queues ) Data Structures Fall 2019 33 / 61

Page 34: Lists, Stacks, and Queuesccf.ee.ntu.edu.tw/~yen/courses/ds19F/chapter-3.pdf · (Lists, Stacks, and Queues ) Data Structures Fall 2019 26 / 61. Linked Lists A linked list is a series

Deleting a Node

(Lists, Stacks, and Queues ) Data Structures Fall 2019 34 / 61

Page 35: Lists, Stacks, and Queuesccf.ee.ntu.edu.tw/~yen/courses/ds19F/chapter-3.pdf · (Lists, Stacks, and Queues ) Data Structures Fall 2019 26 / 61. Linked Lists A linked list is a series

Deleting a Node (Cont’d)

(Lists, Stacks, and Queues ) Data Structures Fall 2019 35 / 61

Page 36: Lists, Stacks, and Queuesccf.ee.ntu.edu.tw/~yen/courses/ds19F/chapter-3.pdf · (Lists, Stacks, and Queues ) Data Structures Fall 2019 26 / 61. Linked Lists A linked list is a series

Destroying the list

∼List(void)I Use the destructor to release all the memory used by the list.I Step through the list and delete each node one by one.

(Lists, Stacks, and Queues ) Data Structures Fall 2019 36 / 61

Page 37: Lists, Stacks, and Queuesccf.ee.ntu.edu.tw/~yen/courses/ds19F/chapter-3.pdf · (Lists, Stacks, and Queues ) Data Structures Fall 2019 26 / 61. Linked Lists A linked list is a series

Variations of Linked Lists

Circular linked listsI The last node points to the first node of the listI How do we know when we have finished traversing the list? (Tip:

check if the pointer of the current node is equal to the head.)

Doubly linked listsI Each node points to not only successor but the predecessorI There are two NULL: at the first and last nodes in the listI Advantage: given a node, it is easy to visit its predecessor.

Convenient to traverse lists backwards

(Lists, Stacks, and Queues ) Data Structures Fall 2019 37 / 61

Page 38: Lists, Stacks, and Queuesccf.ee.ntu.edu.tw/~yen/courses/ds19F/chapter-3.pdf · (Lists, Stacks, and Queues ) Data Structures Fall 2019 26 / 61. Linked Lists A linked list is a series

Doubly-Linked List

insert(X, A): insert node A before X

remove(X)

Problems with operations at ends of list

(Lists, Stacks, and Queues ) Data Structures Fall 2019 38 / 61

Page 39: Lists, Stacks, and Queuesccf.ee.ntu.edu.tw/~yen/courses/ds19F/chapter-3.pdf · (Lists, Stacks, and Queues ) Data Structures Fall 2019 26 / 61. Linked Lists A linked list is a series

Sentinel Nodes

Dummy head and tail nodes to avoid special cases at ends of listDoubly-linked list with sentinel nodes

Empty doubly-linked list with sentinel nodes

(Lists, Stacks, and Queues ) Data Structures Fall 2019 39 / 61

Page 40: Lists, Stacks, and Queuesccf.ee.ntu.edu.tw/~yen/courses/ds19F/chapter-3.pdf · (Lists, Stacks, and Queues ) Data Structures Fall 2019 26 / 61. Linked Lists A linked list is a series

Link Inversion

Forward:· · · A → B → C → D · · ·⇑ ↑

prev pres

· · · ← A B → C → D · · ·⇑ ↑

· · · ← A ← B C → D · · ·⇑ ↑

Backward ...

(Lists, Stacks, and Queues ) Data Structures Fall 2019 40 / 61

Page 41: Lists, Stacks, and Queuesccf.ee.ntu.edu.tw/~yen/courses/ds19F/chapter-3.pdf · (Lists, Stacks, and Queues ) Data Structures Fall 2019 26 / 61. Linked Lists A linked list is a series

Exclusive-Or Doubly Linked List

An XOR linked list compresses the same information into oneaddress field by storing the bitwise XOR (here denoted by

⊕) of

the address for previous and the address for next in one fieldAddr · · · A B C D E · · ·Link ↔ A

⊕C ↔ B

⊕D ↔ C

⊕E

More formally:link(B) = addr(A)

⊕addr(C), link(C) = addr(B)

⊕addr(D), ...

Note: X⊕

X = 0 X⊕

0 = X X⊕

Y = Y⊕

X(X⊕

Y)⊕

Z = X⊕

(Y⊕

Z)

Move forward:at C, take addr(B), XOR it with C’s link value (i.e., B

⊕D), yields

addr(D), and you can continue traversing the list.Move backward: Similar

(Lists, Stacks, and Queues ) Data Structures Fall 2019 41 / 61

Page 42: Lists, Stacks, and Queuesccf.ee.ntu.edu.tw/~yen/courses/ds19F/chapter-3.pdf · (Lists, Stacks, and Queues ) Data Structures Fall 2019 26 / 61. Linked Lists A linked list is a series

C++ Standard Template Library (STL)

Implementation of common data structuresI Available in C++ library, known as Standard Template Library

(STL)I List, stack, queue,I Generally these data structures are called containers or collections

WWW resourcesI www.sgi.com/tech/stlI www.cppreference.com/cppstl.html

(Lists, Stacks, and Queues ) Data Structures Fall 2019 42 / 61

Page 43: Lists, Stacks, and Queuesccf.ee.ntu.edu.tw/~yen/courses/ds19F/chapter-3.pdf · (Lists, Stacks, and Queues ) Data Structures Fall 2019 26 / 61. Linked Lists A linked list is a series

Lists Using STL

Two popular implementation of the List ADTI The vector provides a growable array implementation of the List

ADTF Advantage: it is indexable in constant timeF Disadvantage: insertion and deletion are computationally expensive

I The list provides a doubly linked list implementation of the ListADT

F Advantage: insertion and deletion are cheap provided that theposition of the changes are known

F Disadvantage: list is not easily indexable

Vector and list are class templatesI Can be instantiated with different type of items

(Lists, Stacks, and Queues ) Data Structures Fall 2019 43 / 61

Page 44: Lists, Stacks, and Queuesccf.ee.ntu.edu.tw/~yen/courses/ds19F/chapter-3.pdf · (Lists, Stacks, and Queues ) Data Structures Fall 2019 26 / 61. Linked Lists A linked list is a series

Iterators

Insert and remove from the middle of the listI Require the notion of a positionI In STL a position is represented by a nested type, iteratorI Example: list <string>:: iterator; vector<int>:: iterator

Iterator: Represents position in the containerThree Issues:

I How one gets an Iterator?I What operations the iterators themselves can perform?I Which LIST ADT methods require iterators as parameters?

(Lists, Stacks, and Queues ) Data Structures Fall 2019 44 / 61

Page 45: Lists, Stacks, and Queuesccf.ee.ntu.edu.tw/~yen/courses/ds19F/chapter-3.pdf · (Lists, Stacks, and Queues ) Data Structures Fall 2019 26 / 61. Linked Lists A linked list is a series

Example: The Polynomial ADT

An ADT for single-variable polynomials

f (x) =N∑

i=0

aixi

Array implementation

(Lists, Stacks, and Queues ) Data Structures Fall 2019 45 / 61

Page 46: Lists, Stacks, and Queuesccf.ee.ntu.edu.tw/~yen/courses/ds19F/chapter-3.pdf · (Lists, Stacks, and Queues ) Data Structures Fall 2019 26 / 61. Linked Lists A linked list is a series

The Polynomial ADT

Multiplying two polynomials

P1(x) = 10x1000 + 5x14 + 1

P2(x) = 3x1990 − 2x1492 + 11x + 5

Implementation using a singly linked list

(Lists, Stacks, and Queues ) Data Structures Fall 2019 46 / 61

Page 47: Lists, Stacks, and Queuesccf.ee.ntu.edu.tw/~yen/courses/ds19F/chapter-3.pdf · (Lists, Stacks, and Queues ) Data Structures Fall 2019 26 / 61. Linked Lists A linked list is a series

Stack ADT

Stack is a list where insert and remove take place only at the topOperations: Constant time

I Push - inserts element on top of stackI Pop - removes element from top of stackI Top - returns element at top of stackI Empty, size

LIFO (Last In First Out)

(Lists, Stacks, and Queues ) Data Structures Fall 2019 47 / 61

Page 48: Lists, Stacks, and Queuesccf.ee.ntu.edu.tw/~yen/courses/ds19F/chapter-3.pdf · (Lists, Stacks, and Queues ) Data Structures Fall 2019 26 / 61. Linked Lists A linked list is a series

Stack Implementation

Singly Linked ListI Push - inserts the element at the front of the listI Pop - deletes the element at the front of the listI Top - returns the element at the front of the list

ArrayI Back, push back, pop back implementation from vectorI theArray and topOfStack which is -1 for an empty stackI Push - increment topOfStack and then set theArray[topOfStack] = xI Pop - return the value to theArray[topOfStack] and then decrement

topOfStack

(Lists, Stacks, and Queues ) Data Structures Fall 2019 48 / 61

Page 49: Lists, Stacks, and Queuesccf.ee.ntu.edu.tw/~yen/courses/ds19F/chapter-3.pdf · (Lists, Stacks, and Queues ) Data Structures Fall 2019 26 / 61. Linked Lists A linked list is a series

Stack Implementation (cont’d)

(Lists, Stacks, and Queues ) Data Structures Fall 2019 49 / 61

Page 50: Lists, Stacks, and Queuesccf.ee.ntu.edu.tw/~yen/courses/ds19F/chapter-3.pdf · (Lists, Stacks, and Queues ) Data Structures Fall 2019 26 / 61. Linked Lists A linked list is a series

Applications of Stack

Balancing symbolsI Compiler checks for program syntax errorsI Every right brace, bracket, and parenthesis must correspond to its

left counterpartI The sequence [()] is legal, but [(]) is wrong

Postfix ExpressionsInfix to Postfix ConversionFunction calls

(Lists, Stacks, and Queues ) Data Structures Fall 2019 50 / 61

Page 51: Lists, Stacks, and Queuesccf.ee.ntu.edu.tw/~yen/courses/ds19F/chapter-3.pdf · (Lists, Stacks, and Queues ) Data Structures Fall 2019 26 / 61. Linked Lists A linked list is a series

Balancing Symbols

Balancing symbols: ((()())(()))

(Lists, Stacks, and Queues ) Data Structures Fall 2019 51 / 61

Page 52: Lists, Stacks, and Queuesccf.ee.ntu.edu.tw/~yen/courses/ds19F/chapter-3.pdf · (Lists, Stacks, and Queues ) Data Structures Fall 2019 26 / 61. Linked Lists A linked list is a series

Evaluation of Postfix Expressions

Infix expression: ((1 * 2) + 3) + (4 * 5)Postfix expression: 1 2 * 3 + 4 5 * +

I Unambiguous (no need for parenthesis)I Infix needs parenthesis or else implicit precedence specification to

avoid ambiguityE.g. ”a + b * c” can be ”(a + b) * c” or ”a + (b * c)”

I Postfix expression evaluation uses stackI E.g. Evaluate 1 2 * 3 + 4 5 * +

Rule of postfix expression evaluationI When a number/operand is seen push it onto the stackI When a operator is seen, the operator is applied to the two

numbers (symbols) that are popped from the stack, andI Result is pushed onto the stack

(Lists, Stacks, and Queues ) Data Structures Fall 2019 52 / 61

Page 53: Lists, Stacks, and Queuesccf.ee.ntu.edu.tw/~yen/courses/ds19F/chapter-3.pdf · (Lists, Stacks, and Queues ) Data Structures Fall 2019 26 / 61. Linked Lists A linked list is a series

Infix to Postfix Conversion

When an operand is read, place it onto the outputOperators are not immediately output, so save them somewhereelse which is stackIf a left parenthesis is encountered, stack itStart with an initially empty stackIf we see a right parenthesis, pop the stack, writing symbols untilwe encounter a left parenthesis which is popped but not outputIf we see any other symbols, then we pop the entries from thestack until we find an entry of lower priority. One exception is wenever remove a ”(” from the stack except when processing a ”)”Finally, if we read the end of input, pop the stack until it is empty,writing symbols onto the output

(Lists, Stacks, and Queues ) Data Structures Fall 2019 53 / 61

Page 54: Lists, Stacks, and Queuesccf.ee.ntu.edu.tw/~yen/courses/ds19F/chapter-3.pdf · (Lists, Stacks, and Queues ) Data Structures Fall 2019 26 / 61. Linked Lists A linked list is a series

Infix to Postfix Conversion (Cont’d)

Infix: a + b * c + ( d * e + f ) * gPostfix: a b c * + d e * f + g * +

(Lists, Stacks, and Queues ) Data Structures Fall 2019 54 / 61

Page 55: Lists, Stacks, and Queuesccf.ee.ntu.edu.tw/~yen/courses/ds19F/chapter-3.pdf · (Lists, Stacks, and Queues ) Data Structures Fall 2019 26 / 61. Linked Lists A linked list is a series

Applications of Stack: Function Calls

Programming languages use stack to keep track of function callsWhen a function call occurs

I Push CPU registers and program counter on to stack (activationrecord or stack frame)

I Upon return, restore registers and program counter from top stackframe and pop

(Lists, Stacks, and Queues ) Data Structures Fall 2019 55 / 61

Page 56: Lists, Stacks, and Queuesccf.ee.ntu.edu.tw/~yen/courses/ds19F/chapter-3.pdf · (Lists, Stacks, and Queues ) Data Structures Fall 2019 26 / 61. Linked Lists A linked list is a series

Queue ADT

Queue is a list where insert takes place at the back, but removetakes place at the frontOperations

I Enqueue - inserts element at the back of queueI Dequeue - removes and returns element from the front of the queue

FIFO (First In First Out)

(Lists, Stacks, and Queues ) Data Structures Fall 2019 56 / 61

Page 57: Lists, Stacks, and Queuesccf.ee.ntu.edu.tw/~yen/courses/ds19F/chapter-3.pdf · (Lists, Stacks, and Queues ) Data Structures Fall 2019 26 / 61. Linked Lists A linked list is a series

Queue Implementation of Array

When an item is enqueued, make the rear index move forward.When an item is dequeued, the front index moves by one elementtowards the back of the queue (thus removing the front item, sono copying to neighboring elements is needed).(rear) XXXXOOOOO (front)

OXXXXOOOO (after 1 dequeue, and 1 enqueue)OOXXXXXOO after another dequeue, and 2 enqueues)OOOOXXXXX (after 2 more dequeues, and 2 enqueues)

The problem here is that the rear index cannot move beyond thelast element in the array.Using a circular array

I OOOOO7963→ 4OOOO7963 (after Enqueue(4))

(Lists, Stacks, and Queues ) Data Structures Fall 2019 57 / 61

Page 58: Lists, Stacks, and Queuesccf.ee.ntu.edu.tw/~yen/courses/ds19F/chapter-3.pdf · (Lists, Stacks, and Queues ) Data Structures Fall 2019 26 / 61. Linked Lists A linked list is a series

Empty or Full?

Empty queue:I back = front - 1

Full queue?I the same!I Reason: n values to represent n + 1 states

SolutionsI Use a boolean variable to say explicitly whether the queue is empty

or notI Make the array of size n+1 and only allow n elements to be storedI Use a counter of the number of elements in the queue

(Lists, Stacks, and Queues ) Data Structures Fall 2019 58 / 61

Page 59: Lists, Stacks, and Queuesccf.ee.ntu.edu.tw/~yen/courses/ds19F/chapter-3.pdf · (Lists, Stacks, and Queues ) Data Structures Fall 2019 26 / 61. Linked Lists A linked list is a series

Queue Implementation based on Linked List

(Lists, Stacks, and Queues ) Data Structures Fall 2019 59 / 61

Page 60: Lists, Stacks, and Queuesccf.ee.ntu.edu.tw/~yen/courses/ds19F/chapter-3.pdf · (Lists, Stacks, and Queues ) Data Structures Fall 2019 26 / 61. Linked Lists A linked list is a series

Queue Implementation based on Linked List (Cont’d)

(Lists, Stacks, and Queues ) Data Structures Fall 2019 60 / 61

Page 61: Lists, Stacks, and Queuesccf.ee.ntu.edu.tw/~yen/courses/ds19F/chapter-3.pdf · (Lists, Stacks, and Queues ) Data Structures Fall 2019 26 / 61. Linked Lists A linked list is a series

Applications of Queue

Job scheduling, e.g., Jobs submitted to a line printerCustomer service calls are generally placed on a queue when alloperators are busyPriority queuesGraph traversalsQueuing theory

(Lists, Stacks, and Queues ) Data Structures Fall 2019 61 / 61