chapter 6: sequences : vectors and lists col 106 shweta agrawal

37
Chapter 6: Sequences : vectors and lists COL 106 Shweta Agrawal

Upload: lee-griffin

Post on 21-Dec-2015

224 views

Category:

Documents


4 download

TRANSCRIPT

Page 1: Chapter 6: Sequences : vectors and lists COL 106 Shweta Agrawal

Chapter 6:Sequences : vectors and lists

COL 106

Shweta Agrawal

Page 2: Chapter 6: Sequences : vectors and lists COL 106 Shweta Agrawal

Highlights from last class

• Parenthesis matching using stack• Growable array based stack

• Incremental strategy• Doubling strategy

• Queue using circular array or singly linked list• C++ interface for stack and queues• Dequeue (“deck”) using doubly linked list• Stacks or queues using dequeue

04/19/23 00:22Vectors 2

Page 3: Chapter 6: Sequences : vectors and lists COL 106 Shweta Agrawal

Containers

• Some time ago we saw the notion of a class in C++ • A class is like an ADT – it contains data members and also

contains function members that specify how the data should be accessed

• Classes provided by STL are organized in various groups• Particularly important is the container group• A container is a data structure that stores a collection of

objects• Classified into associative containers and sequence

containers (called just sequences)04/19/23 00:22

3

Page 4: Chapter 6: Sequences : vectors and lists COL 106 Shweta Agrawal

Sequences

• Suppose we have a collection S of n elements stored in a linear order, so that we can refer to the elements in S as first, second, third, and so on.

• Such a collection is generically referred to as a sequence. • We can uniquely refer to each element e in S using an integer

in the range [0,n−1] that is equal to the number of elements of S that precede e in S.

• The index of an element e in S is the number of elements that are before e in S. The rank of an element is defined to be one more than its index

04/19/23 00:22Vectors 4

Page 5: Chapter 6: Sequences : vectors and lists COL 106 Shweta Agrawal

Examples of sequences

• Array : implements a compile-time non-resizeable array.

• Vector : implements an array with fast random access and an ability to automatically resize when appending elements.

• Deque : implements a double ended queue with comparatively fast random access.

• List : implements a doubly linked list.• Forward_list : implements a singly linked list

04/19/23 00:22Vectors 5

Page 6: Chapter 6: Sequences : vectors and lists COL 106 Shweta Agrawal

Vectors • The Vector ADT extends the

notion of array

• An element can be accessed, inserted or removed by specifying its index/rank

• An exception is thrown if an incorrect rank is specified (e.g., a negative rank)

• Main vector operations:– elemAtRank(int r): returns the

element at rank r without removing it

– replaceAtRank(int r, Object o): replace the element at rank r with o

– insertAtRank(int r, Object o): insert a new element o to have rank r

– removeAtRank(int r): removes the element at rank r

• Additional operations size() and isEmpty()

04/19/23 00:22Vectors 6

Page 7: Chapter 6: Sequences : vectors and lists COL 106 Shweta Agrawal

Array-based Vector

• Use an array V of size N• A variable n keeps track of the size of the vector

(number of elements stored)• Operation elemAtRank(r) is implemented in O(1) time

by returning V[r]

04/19/23 00:22Vectors 7

V

0 1 2 nr

N-10

Page 8: Chapter 6: Sequences : vectors and lists COL 106 Shweta Agrawal

Array based Vector: Insertion

• In operation insertAtRank(r,o) we need to make room for the new element by shifting forward the n r elements V[r], …, V[n 1]

• In the worst case (r 0), this takes O(n) time

04/19/23 00:22Vectors 8

V

0 1 2 nr

V

0 1 2 nr

V

0 1 2 nor

Page 9: Chapter 6: Sequences : vectors and lists COL 106 Shweta Agrawal

Deletion• In operation removeAtRank(r) we need to fill the hole

left by the removed element by shifting backward the n r 1 elements V[r 1], …, V[n 1]

• In the worst case (r 0), this takes O(n) time

04/19/23 00:22Vectors 9

V

0 1 2 nr

V

0 1 2 nor

V

0 1 2 nr

Page 10: Chapter 6: Sequences : vectors and lists COL 106 Shweta Agrawal

Performance

• In the array based implementation of a Vector– The space used by the data structure is O(n)– Size(), isEmpty(), elemAtRank(r) and replaceAtRank(r,o)

run in O(1) time– insertAtRank(r,o) and removeAtRank(r) run in O(n) time

• If we use the array in a circular fashion, insertAtRank(0,o) and removeAtRank(0) run in O(1) time (how?)

• In an insertAtRank(r,o) operation, when the array is full, instead of throwing an exception, we can replace the array with a larger one

04/19/23 00:22Vectors 10

Page 11: Chapter 6: Sequences : vectors and lists COL 106 Shweta Agrawal

Exercise:

• Implement the Deque ADT using Vector functions– Deque functions:

• first(), last(), insertFirst(e), insertLast(e), removeFirst(), removeLast(), size(), isEmpty()

– Vector functions: • elemAtRank( r), replaceAtRank(r,e), insertAtRank(r,e),

removeAtRank(r ), size(), isEmpty()

04/19/23 00:22Vectors 11

Page 12: Chapter 6: Sequences : vectors and lists COL 106 Shweta Agrawal

Exercise Solution:

• Implement the Deque ADT using Vector functions– Deque functions: first(), last(), insertFirst(e), insertLast(e), removeFirst(), removeLast(), size(), isEmpty()– Vector functions: elemAtRank( r), replaceAtRank(r,e), insertAtRank(r,e), removeAtRank(r ), size(), isEmpty()

– Deque function : Realization using Vector Functions– size() and isEmpty() fcns can simply call Vector fcns

directly– first() => elemAtRank(0)– last() => elemAtRank(size()-1)– insertFirst(e) => insertAtRank(0,e)– insertLast(e) => insertAtRank(size(), e)– removeFirst() => removeAtRank(0)– removeLast() => removeAtRank(size()-1)

04/19/23 00:22Vectors 12

Page 13: Chapter 6: Sequences : vectors and lists COL 106 Shweta Agrawal

STL vector class

• Functions in the STL vector class (incomplete)– Size(), capacity() - return #elts in vector, #elts vector can hold– empty() - boolean– Operator[r] - returns reference to elt at rank r (no index check)– At( r) - returns reference to elt at rank r (index checked)– Front(), back() - return references to first/last elts– push_back(e) - insert e at end of vector– pop_back() - remove last elt– vector(n) - creates a vector of size n

• Similarities & Differences with book’s Vector ADT– STL assignment v[r]=e is equivalent to v.replaceAtRank(r,e)– No direct STL counterparts of insertAtRank( r) & removeAtRank( r)– STL also provides more general functions for inserting & removing from

arbitrary positions in the vector - these use iterators

04/19/23 00:22Vectors13

Page 14: Chapter 6: Sequences : vectors and lists COL 106 Shweta Agrawal

Stacks versus Vectors• If you can only push_back and pop_back, then

this is LIFO access.• What is the difference from a stack?• Interface is different. For example, can access

elements in the middle in a vector

14

vs

Page 15: Chapter 6: Sequences : vectors and lists COL 106 Shweta Agrawal

Vectors vs Arrays• Apart from usual index operator (“[ ]”), elements can be accessed

by member function at which performs range checking.

• Unlike C++ arrays, STL vectors can be dynamically resized

• When an STL vector of class objects is destroyed, it automatically invokes the destructor for each of its elements. With C++ arrays, it is the obligation of the programmer to do this explicitly.

• Several functions that operate on entire vectors, not just on individual elements. E.g. : copy all or part of one vector to another, compare the contents of two vectors, insert and erase multiple elements. 15

Page 16: Chapter 6: Sequences : vectors and lists COL 106 Shweta Agrawal

Accessing vector elements

• Vectors support dynamic size change• Contiguous blocks of memory unlikely to be

found, unlike array• Arrays use index to traverse elements• How can one traverse elements of a vector if

they are stored non-contiguously?• How to keep track of the position of an

element though its index may keep changing?

16

Using Position and Iterator ADTs

Page 17: Chapter 6: Sequences : vectors and lists COL 106 Shweta Agrawal

Position ADT • Say vector contains an element “Delhi”

that we want to keep track of• The index of the element may keep

changing depending on insert/delete operations

• A position s, may be associated with the element Delhi (say at time of insertion)

• s lets us access Delhi via s.element() even if the index of Delhi changes in the container, unless we explicitly remove s

• A position ADT is associated with a particular container.

17

Delhi

s

Page 18: Chapter 6: Sequences : vectors and lists COL 106 Shweta Agrawal

Sequences 18

Iterator ADT

• Abstracts the process of scanning through a container• Encapsulates the notions of “place” and “next”• Extends the position ADT by adding a traversal capability• Generic and specialized iterators• ObjectIterator hasNext()

nextObject()object()

Page 19: Chapter 6: Sequences : vectors and lists COL 106 Shweta Agrawal

Example using Iterator

19

Page 20: Chapter 6: Sequences : vectors and lists COL 106 Shweta Agrawal

C++ STL support for Iterators

• Some functions supported by STL containers– Begin(), end() - return iterators to beginning or end of

container– Insert(I,e) - insert e just before the position indicated

by iterator I– Erase(I) - removes the elt at the position indicated by I

• The functions can be used to insert/remove elts from arbitrary positions in the STL vector and list

04/19/23 00:22Vectors 20

Page 21: Chapter 6: Sequences : vectors and lists COL 106 Shweta Agrawal

Vector Summary

• Vector Operation Complexity for Different Implementations

04/19/23 00:22Vectors 21

Array Fixed-Size or Expandable

ListSingly or Doubly Linked

RemoveAtRank(r),InsertAtRank(r,o)

O(1) Best Case (r=0,n)O(n) Worst CaseO(n) Average Case

?

elemAtRank(r), ReplaceAtRank(r,o)

O(1) ?

Size(), isEmpty() O(1) ?

Page 22: Chapter 6: Sequences : vectors and lists COL 106 Shweta Agrawal

Lists

04/19/23 00:22Vectors 22

Page 23: Chapter 6: Sequences : vectors and lists COL 106 Shweta Agrawal

Outline and Reading

• Singly linked list• Position ADT (§6.2.1)• List ADT (§6.2.2)• Doubly linked list (§ 6.2.3)• Sequence ADT (§6.3.1)• Implementations of the sequence ADT (§6.3.2-3)• Iterators (§6.2.5)

04/19/23 00:22Vectors 23

Page 24: Chapter 6: Sequences : vectors and lists COL 106 Shweta Agrawal

Position ADT• As in vectors, the Position ADT models the notion of place

within a data structure where a single object is stored• Positions provide a unified view of diverse ways of storing

data, such as– a cell of an array– a node of a linked list

• Member functions:– Object& element(p): returns the element stored at this

position– bool isNull(): returns true if this is a null position

04/19/23 00:22Vectors 24

Page 25: Chapter 6: Sequences : vectors and lists COL 106 Shweta Agrawal

List ADT

• The List ADT models a sequence of positions storing arbitrary objects– establishes a before/after

relation between positions• It allows for insertion and

removal in the “middle” • Query methods:

– isFirst(p), isLast(p)• Generic methods:

– size(), isEmpty()

• Accessor methods:– first(), last()– before(p), after(p)

• Update methods:– replaceElement(p, o),

swapElements(p, q) – insertBefore(p, o),

insertAfter(p, o),– insertFirst(o), insertLast(o)– remove(p)

25

ADT that captures linked lists

Page 26: Chapter 6: Sequences : vectors and lists COL 106 Shweta Agrawal

List ADT

• Query methods:– isFirst(p), isLast(p) :

• return boolean indicating if the given position is the first or last, resp.

• Accessor methods– first(), last():

• return the position of the first or last, resp., element of S• an error occurs if S is empty

– before(p), after(p): • return the position of the element of S preceding or

following, resp, the one at position p• an error occurs if S is empty, or p is the first or last, resp.,

position

04/19/23 00:22Vectors 26

Page 27: Chapter 6: Sequences : vectors and lists COL 106 Shweta Agrawal

List ADT• Update Methods

– replaceElement(p, e)• Replace the element at position p with e

– swapElements(p, q) • Swap the elements stored at positions p & q

– insertBefore(p, o), insertAfter(p, o),• Insert a new element o into S before or after, resp., position p• Output: position of the newly inserted element

– insertFirst(o), insertLast(o)• Insert a new element o into S as the first or last, resp., element• Output: position of the newly inserted element

– remove(p)• Remove the element at position p from S

04/19/23 00:22Vectors 27

Page 28: Chapter 6: Sequences : vectors and lists COL 106 Shweta Agrawal

Exercise:

• Describe how to implement the following list ADT operations using a singly-linked list– list ADT operations: first(), last(), before(p),

after(p)– For each operation, explain how it is

implemented and provide the running time

04/19/23 00:22Vectors 28

• A singly linked list concrete data structure consists of a sequence of nodes

• Each node stores• element• link to the next node

next

elem node

A B C D

Page 29: Chapter 6: Sequences : vectors and lists COL 106 Shweta Agrawal

Exercise:• Describe how to implement the following

list ADT operations using a doubly-linked list– list ADT operations: first(), last(), before(p),

after(p)– For each operation, explain how it is

implemented and provide the running time

04/19/23 00:22Vectors

29

trailerheader

elements

prev next

elem

node• Doubly-Linked List Nodes implement Position and store:

• element• link to previous node• link to next node

• Special trailer and header nodes

Page 30: Chapter 6: Sequences : vectors and lists COL 106 Shweta Agrawal

Insertion• We visualize operation insertAfter(p, X) which returns position q

04/19/23 00:22Vectors 30

A B X C

A B C

p

A B C

p

X

q

p q

p

q

Page 31: Chapter 6: Sequences : vectors and lists COL 106 Shweta Agrawal

Deletion• We visualize remove(p), where p = last()

04/19/23 00:22Vectors 31

A B C D

p

A B C

D

p

A B C

Page 32: Chapter 6: Sequences : vectors and lists COL 106 Shweta Agrawal

Performance

• In the implementation of the List ADT by means of a doubly linked list– The space used by a list with n elements is O(n)– The space used by each position of the list is

O(1)– All the operations of the List ADT run in O(1)

time– Operation element() of the

Position ADT runs in O(1) time

04/19/23 00:22Vectors 32

Page 33: Chapter 6: Sequences : vectors and lists COL 106 Shweta Agrawal

STL list class• Functions in the STL list class

– Size() - return #elts in list, empty() - boolean– Front(), back() - return references to first/last elts– Push_front(e), push_back(e) - insert e at front/end – Pop_front(), pop_back() - remove first/last elt– List() - creates an empty list

• Similarities & Differences with book’s List ADT– STL front() & back() correspond to first() & last() except the STL functions

return the element & not its position– STL push() & pop() are equiv to List ADT insert and remove when applied

to the beginning & end of the list– STL also provides fcns for inserting & removing from arbitrary positions in

the list - these use iterators

04/19/23 00:22Vectors 33

Page 34: Chapter 6: Sequences : vectors and lists COL 106 Shweta Agrawal

List Summary• List Operation Complexity for different

implementations

04/19/23 00:22Vectors 34

List Singly-Linked List Doubly- Linked

first(), last(), after(p)insertAfter(p,o), replaceElement(p,o), swapElements(p,q)

O(1) O(1)

before(p), insertBefore(p,o), remove(p)

O(n) WC & ACO(1) BC

O(1)

Size(), isEmpty() O(1) O(1)

Page 35: Chapter 6: Sequences : vectors and lists COL 106 Shweta Agrawal

Sequence ADT

• The Sequence ADT is the union of the Vector and List ADTs

• Elements accessed by– Rank, or– Position

• Generic methods:– size(), isEmpty()

• Vector-based methods:– elemAtRank(r),

replaceAtRank(r, o), insertAtRank(r, o), removeAtRank(r)

• List-based methods:– first(), last(), before(p),

after(p), replaceElement(p, o), swapElements(p, q), insertBefore(p, o), insertAfter(p, o), insertFirst(o), insertLast(o), remove(p)

• Bridge methods:– atRank(r), rankOf(p)

04/19/23 00:22Vectors 35

Generalizes vectors and lists

Page 36: Chapter 6: Sequences : vectors and lists COL 106 Shweta Agrawal

Array-based Implementation

• We use a circular array storing positions

• A position object stores:– Element– Rank

• Indices f and l keep track of first and last positions

04/19/23 00:22Vectors 36

0 1 2 3

positions

elements

S

lf

Page 37: Chapter 6: Sequences : vectors and lists COL 106 Shweta Agrawal

Sequence Implementations

04/19/23 00:22Vectors 37

Operation Array List

size, isEmpty 1 1

atRank, rankOf, elemAtRank 1 n

first, last, before, after 1 1

replaceElement, swapElements 1 1

replaceAtRank 1 n

insertAtRank, removeAtRank n n

insertFirst, insertLast 1 1

insertAfter, insertBefore n 1

remove n 1