Top Banner
Lists, Stacks, Queues, Trees, Hash Lists, Stacks, Queues, Trees, Hash Tables Tables Basic Data Basic Data Structures Structures
78

Lists, Stacks, Queues, Trees, Hash Tables Basic Data Structures.

Mar 26, 2015

Download

Documents

Thomas Kelly
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Lists, Stacks, Queues, Trees, Hash Tables Basic Data Structures.

Lists, Stacks, Queues, Trees, Hash TablesLists, Stacks, Queues, Trees, Hash Tables

Basic Data Basic Data StructuresStructures

Page 2: Lists, Stacks, Queues, Trees, Hash Tables Basic Data Structures.

ContentsContents

• Abstract Data Types (ADT)Abstract Data Types (ADT)

• Lists – Lists – ArrayListArrayList Class Class

• Stacks – Stacks – StackStack Class Class

• Queues – Queues – QueueQueue Class Class

• Trees – Terminology and TypesTrees – Terminology and Types

• Dictionaries – Dictionaries – HashMapHashMap Class Class

Page 3: Lists, Stacks, Queues, Trees, Hash Tables Basic Data Structures.

Abstract Data TypesAbstract Data Types

• An Abstract Data Type (ADT) is a data type An Abstract Data Type (ADT) is a data type together with the operations, whose together with the operations, whose properties are specified independently of any properties are specified independently of any particular implementationparticular implementation

• ADT are set of definitions of operations (like ADT are set of definitions of operations (like the interfaces in Java)the interfaces in Java)

• Can have several different implementationsCan have several different implementations

• Different implementations can have different Different implementations can have different efficiencyefficiency

Page 4: Lists, Stacks, Queues, Trees, Hash Tables Basic Data Structures.

Basic Data StructuresBasic Data Structures

• Linear structuresLinear structures• Lists: Variable-sizeLists: Variable-size• Stacks: LIFO (last in first out) structureStacks: LIFO (last in first out) structure• Queues: FIFO (first in first out) structureQueues: FIFO (first in first out) structure

• TreesTrees• Dictionaries (maps)Dictionaries (maps)• Contain pairs (key, value)Contain pairs (key, value)• Hash tables: Unordered lists which use a Hash tables: Unordered lists which use a

‘hash function’ to insert and search‘hash function’ to insert and search

Page 5: Lists, Stacks, Queues, Trees, Hash Tables Basic Data Structures.

What Is a List?What Is a List?

Page 6: Lists, Stacks, Queues, Trees, Hash Tables Basic Data Structures.

The List ADTThe List ADT

• List is linear data structure (container) that List is linear data structure (container) that contains a sequence of elements (objects)contains a sequence of elements (objects)

• Has variable sizeHas variable size

• Objects are arranged linearlyObjects are arranged linearly

• Can be implemented in several waysCan be implemented in several ways

• Statically (using array)Statically (using array)

• Dynamically (linked implementation)Dynamically (linked implementation)

• Using the Using the ArrayListArrayList class class

Page 7: Lists, Stacks, Queues, Trees, Hash Tables Basic Data Structures.

Static and Linked ListsStatic and Linked Lists

Page 8: Lists, Stacks, Queues, Trees, Hash Tables Basic Data Structures.

Static ListStatic List

• Implemented by an arrayImplemented by an array

• Provide direct access by indexProvide direct access by index

• Usually has limited capacityUsually has limited capacity

• Resizing is slow operationResizing is slow operation

• Slow insert and deletionSlow insert and deletion

00 11 22 33 44 55 66 77 88

1111 77 1818 1414LL 55 22 3333 4747 33

Page 9: Lists, Stacks, Queues, Trees, Hash Tables Basic Data Structures.

Linked ListLinked List

• Dynamic (pointer-based) implementationDynamic (pointer-based) implementation

• Different formsDifferent forms

• Singly-linked and doubly-linkedSingly-linked and doubly-linked

• Sorted and UnsortedSorted and Unsorted

• Singly-linked List - each “Object” has “Singly-linked List - each “Object” has “valuevalue” ” and “and “nextnext” fields” fields

1111

nextnext

77

nextnext

1818

nextnext

1414

nextnextheadhead

nullnull

Page 10: Lists, Stacks, Queues, Trees, Hash Tables Basic Data Structures.

1111

nextnext

prevprev

Linked List (2)Linked List (2)

• Doubly-linked List - each “Object” has Doubly-linked List - each “Object” has ““valuevalue”, “”, “nextnext” and “” and “prevprev” fields” fields

headheadtailtail

77

nextnext

prevprev

1818

nextnext

prevprev

1414

nextnext

prevprevnullnull

nullnull

Page 11: Lists, Stacks, Queues, Trees, Hash Tables Basic Data Structures.

Using theUsing theArrayListArrayList classclass

Page 12: Lists, Stacks, Queues, Trees, Hash Tables Basic Data Structures.

The The java.util.ArrayListjava.util.ArrayList ClassClass

• Implements the list data structure using an Implements the list data structure using an array whose size is dynamically increased array whose size is dynamically increased as neededas needed• Allocates in advance buffer space for new Allocates in advance buffer space for new

elements (for better performance)elements (for better performance)

• Insertion methods:Insertion methods:• add(Object)add(Object) – adds an object at the end – adds an object at the end• addadd(index(index,, Object)Object) – inserts an object to – inserts an object to

the list at a specified positionthe list at a specified position

• size()size() – returns the number of elements – returns the number of elements

Page 13: Lists, Stacks, Queues, Trees, Hash Tables Basic Data Structures.

The The ArrayListArrayList Class Class

• Deletion methods:Deletion methods:

• remove(Object)remove(Object) – removes the first – removes the first occurrence of a specific objectoccurrence of a specific object

• remove(remove(index)index) – removes the element at the – removes the element at the specified positionspecified position

• clear()clear() – removes all elements – removes all elements

• Other supported methods:Other supported methods:

• ccontains()ontains(),, ttoArray()oArray()

Page 14: Lists, Stacks, Queues, Trees, Hash Tables Basic Data Structures.

The The ArrayListArrayList Class(2) Class(2)

• ArrayListArrayList can contain any data type can contain any data type• Elements are added directlyElements are added directly

• Typecasting is required when extracting Typecasting is required when extracting elements unless we use Genericselements unless we use Generics

• Converting to arrayConverting to array

List list = new ArrayList();List list = new ArrayList();list.list.aadd(5); // Add integer valuedd(5); // Add integer valuelist.list.aadd("some string"); // Add string valuedd("some string"); // Add string value

int firstElement = ((Integer)int firstElement = ((Integer)(list.get(0))).intValue();(list.get(0))).intValue();String secondElement = (String)list.get(1); String secondElement = (String)list.get(1);

Integer[] arr = list.toArray(new Integer[] arr = list.toArray(new Integer[list.size()]);Integer[list.size()]);

Page 15: Lists, Stacks, Queues, Trees, Hash Tables Basic Data Structures.

What are GenericsWhat are Generics

• Generics are classes or interfaces that can Generics are classes or interfaces that can be instantiated with a variety of typesbe instantiated with a variety of types

• They have 1 or more formal type parametersThey have 1 or more formal type parameters

• When using a generic you specify an actual When using a generic you specify an actual typetype

List<String> list = new ArrayList<String>();List<String> list = new ArrayList<String>();String s = new String("String s = new String("li1li1");");list.add(s);list.add(s);

list.add(5); // This will cause compile time errorlist.add(5); // This will cause compile time error

Specifies that String is actual Specifies that String is actual type of this type of this ListList

Specifies that String is actual Specifies that String is actual type of this type of this ListList

5 is not a 5 is not a StringString

5 is not a 5 is not a StringString

Page 16: Lists, Stacks, Queues, Trees, Hash Tables Basic Data Structures.

Primes[n..m] – ExamplePrimes[n..m] – Example

• Find all prime numbers in a specified intervalFind all prime numbers in a specified intervalpublic static ArrayList<Integer>public static ArrayList<Integer>

getPrimes(int start, int end) {getPrimes(int start, int end) { List<Integer> primesList = List<Integer> primesList =

new ArrayList<Integer>();new ArrayList<Integer>(); for (int num = start; num <= end; num++) {for (int num = start; num <= end; num++) { boolean prime = true;boolean prime = true; for (int div = 2; div <= Math.sqrt(num); div++) {for (int div = 2; div <= Math.sqrt(num); div++) { if (num % div == 0) {if (num % div == 0) { prime = false;prime = false; break;break; }} }} if (prime) {if (prime) { primesList.add(num);primesList.add(num); }} }} return primesList;return primesList;}}

Page 17: Lists, Stacks, Queues, Trees, Hash Tables Basic Data Structures.

Primes[n..m]Primes[n..m]Live DemoLive Demo

Page 18: Lists, Stacks, Queues, Trees, Hash Tables Basic Data Structures.

Union and Intersection of Lists Union and Intersection of Lists – Example– Example

public static Integer[] union(Integer[] firstArr,public static Integer[] union(Integer[] firstArr,Integer[] secondArr) {Integer[] secondArr) {

List<Integer> union = new ArrayList<Integer>();List<Integer> union = new ArrayList<Integer>();

for (Integer item : firstArr) {for (Integer item : firstArr) { union.add(item);union.add(item); }}

for (Integer item : secondArr) {for (Integer item : secondArr) { if (!union.contains(item)) {if (!union.contains(item)) { union.add(item);union.add(item); }} }}

return union.toArray(new Integer[union.size()]);return union.toArray(new Integer[union.size()]);}}

//Example continues...//Example continues...

Page 19: Lists, Stacks, Queues, Trees, Hash Tables Basic Data Structures.

Union and Intersection of Lists Union and Intersection of Lists – Example(2)– Example(2)

public static Integer[] intersect(Integer[] firstArr,public static Integer[] intersect(Integer[] firstArr,Integer[] secondArr) {Integer[] secondArr) {

List<Integer> intersect =List<Integer> intersect =new ArrayList<Integer>();new ArrayList<Integer>();

for (Integer item : firstArr) {for (Integer item : firstArr) { if (Arrays.binarySearch(secondArr, item) >= 0) {if (Arrays.binarySearch(secondArr, item) >= 0) { intersect.add(item);intersect.add(item); }} }}

return intersect.toArray(return intersect.toArray(new Integer[intersect.size()]);new Integer[intersect.size()]);

}}

Page 20: Lists, Stacks, Queues, Trees, Hash Tables Basic Data Structures.

Union and IntersectionUnion and IntersectionLive DemoLive Demo

Page 21: Lists, Stacks, Queues, Trees, Hash Tables Basic Data Structures.

What is a Stack?What is a Stack?

Page 22: Lists, Stacks, Queues, Trees, Hash Tables Basic Data Structures.

The Stack ADTThe Stack ADT

• LIFO (last in first out) structureLIFO (last in first out) structure

• Elements inserted (push) at “top”Elements inserted (push) at “top”

• Elements removed (pop) from “top”Elements removed (pop) from “top”

• Can be implemented in several waysCan be implemented in several ways

• Statically (using array)Statically (using array)

• Dynamically (linked implementation)Dynamically (linked implementation)

• Using the Using the StackStack class class

Page 23: Lists, Stacks, Queues, Trees, Hash Tables Basic Data Structures.

Static StackStatic Stack

• Array-based (static) implementationArray-based (static) implementation

• Usually has limited capacityUsually has limited capacity

• Has Has top top variable, pointing to the topvariable, pointing to the top

• IsEMPTY(IsEMPTY(SS))

• Check if Check if S.topS.top = -1 = -1

00 11 22 33 44 55 66 77 88

1111 77 1818 1414SS

toptop

Page 24: Lists, Stacks, Queues, Trees, Hash Tables Basic Data Structures.

Linked StackLinked Stack

• Dynamic (pointer-based) implementationDynamic (pointer-based) implementation

• Each “object” has “value” and “next” fieldsEach “object” has “value” and “next” fields

• Dynamically create and delete objectsDynamically create and delete objects

1111

nextnext

77

nextnext

1818

nextnext

1414

nextnext

toptopnullnull

Page 25: Lists, Stacks, Queues, Trees, Hash Tables Basic Data Structures.

Using the Using the StackStack class class

Page 26: Lists, Stacks, Queues, Trees, Hash Tables Basic Data Structures.

The The StackStack Class – Overview Class – Overview

• Implements the stack data structure using an Implements the stack data structure using an array whose size is dynamically increased as array whose size is dynamically increased as neededneeded

• Major methods:Major methods:

• push(object)push(object) – inserts elements to the – inserts elements to the stackstack

• pop()pop() – removes and returns the top element – removes and returns the top element from the stackfrom the stack

• peek()peek() – returns the top element of the stack – returns the top element of the stack without removing itwithout removing it

Page 27: Lists, Stacks, Queues, Trees, Hash Tables Basic Data Structures.

The The StackStack Class – More Class – More MethodsMethods

• Other methods:Other methods:

• size()size() – returns the number of elements – returns the number of elements

• clear()clear() – removes all elements – removes all elements

• contains(object)contains(object) – determines whether – determines whether given element is in the stackgiven element is in the stack

• toArray()toArray() – converts the stack to array – converts the stack to array

Page 28: Lists, Stacks, Queues, Trees, Hash Tables Basic Data Structures.

Using the Using the StackStack class class

ExamplesExamples

Page 29: Lists, Stacks, Queues, Trees, Hash Tables Basic Data Structures.

StackStack – Example – Example

• Using Using push()push(), , pop()pop() and and peek()peek() methods methods

public static void main(String[] args) {public static void main(String[] args) { Stack<String> stack = new Stack<String>();Stack<String> stack = new Stack<String>();

stack.push("1. Ivan");stack.push("1. Ivan"); stack.push("2. Nikolay");stack.push("2. Nikolay"); stack.push("3. Maria");stack.push("3. Maria"); stack.push("4. George");stack.push("4. George");

System.out.println("Top = " + stack.peek());System.out.println("Top = " + stack.peek());

while (stack.size() > 0)while (stack.size() > 0) {{ String personName = stack.pop();String personName = stack.pop(); System.out.println(personName);System.out.println(personName); }}}}

Page 30: Lists, Stacks, Queues, Trees, Hash Tables Basic Data Structures.

Using the Using the StackStack class class

Live DemoLive Demo

Page 31: Lists, Stacks, Queues, Trees, Hash Tables Basic Data Structures.

Matching Brackets – ExampleMatching Brackets – Example

• We are given an arithmetical expression with We are given an arithmetical expression with brackets that can be nested. We want to brackets that can be nested. We want to extract all parts of the expression that are extract all parts of the expression that are closed in brackets.closed in brackets.

• Example: 1 + (3 + 2 - (2+3) * 4 - ((3+1)*(4-2)))Example: 1 + (3 + 2 - (2+3) * 4 - ((3+1)*(4-2)))

• Result:Result:• (2+3)(2+3)

• (3+1)(3+1)

• (4-2)(4-2)

• ((3+1)*(4-2))((3+1)*(4-2))

• (3 + 2 - (2+3) * 4 - ((3+1)*(4-2)))(3 + 2 - (2+3) * 4 - ((3+1)*(4-2)))

Page 32: Lists, Stacks, Queues, Trees, Hash Tables Basic Data Structures.

Matching Brackets – Solution Matching Brackets – Solution with a Stackwith a Stack

String expression =String expression ="1 + (3 + 2 - (2+3) * 4 - ((3+1)*(4-2)))";"1 + (3 + 2 - (2+3) * 4 - ((3+1)*(4-2)))";

Stack<Integer> stack = new Stack<Integer>();Stack<Integer> stack = new Stack<Integer>();

for (int i = 0; i < expression.length(); i++) {for (int i = 0; i < expression.length(); i++) { char ch = expression.charAt(i);char ch = expression.charAt(i); if (ch == '(') {if (ch == '(') { stack.push(i);stack.push(i); } else if (ch == ')') {} else if (ch == ')') { int startIndex = (int) stack.pop();int startIndex = (int) stack.pop(); String contents = String contents =

expression.substring(startIndex, i + 1);expression.substring(startIndex, i + 1); System.out.println(contents);System.out.println(contents); }}}}

Page 33: Lists, Stacks, Queues, Trees, Hash Tables Basic Data Structures.

Matching BracketsMatching Brackets

Live DemoLive Demo

Page 34: Lists, Stacks, Queues, Trees, Hash Tables Basic Data Structures.

What is a Queue?What is a Queue?

Page 35: Lists, Stacks, Queues, Trees, Hash Tables Basic Data Structures.

The Queue ADTThe Queue ADT

• FIFO (first in first out) structureFIFO (first in first out) structure• Elements inserted at tail (enqueue)Elements inserted at tail (enqueue)• Elements removed from head (Elements removed from head (dequeuedequeue))• Useful in many situationsUseful in many situations• Processing jobs, print queues, messagesProcessing jobs, print queues, messages

• Can be implemented in several waysCan be implemented in several ways• Statically (using array)Statically (using array)• Dynamically (using pointers)Dynamically (using pointers)• Using the Using the LinkedListLinkedList class class

Page 36: Lists, Stacks, Queues, Trees, Hash Tables Basic Data Structures.

Static QueueStatic Queue

• Static (array-based) implementationStatic (array-based) implementation

• Queue has limited (fixed) capacityQueue has limited (fixed) capacity

• Implement as a “circular array”Implement as a “circular array”

• Maintain Maintain Q.CapacityQ.Capacity and and Q.LengthQ.Length

• Has Has headhead and and tailtail variables, pointing variables, pointing

to the head and the tailto the head and the tail

00 11 22 33 44 55 66 77 88

1111 77 1818 1414QQ

headhead tailtail

Page 37: Lists, Stacks, Queues, Trees, Hash Tables Basic Data Structures.

Linked QueueLinked Queue

• Dynamic (pointer-based) implementationDynamic (pointer-based) implementation

• Each “object” has “Each “object” has “valuevalue” and “” and “nextnext” fields” fields

• Dynamically create and delete objectsDynamically create and delete objects

1111

nextnext

77

nextnext

1818

nextnext

1414

nextnext

headhead tailtailnullnull

Page 38: Lists, Stacks, Queues, Trees, Hash Tables Basic Data Structures.

Using the Using the LinkedListLinkedList class class

Page 39: Lists, Stacks, Queues, Trees, Hash Tables Basic Data Structures.

The The LinkedListLinkedList Class – Class – OverviewOverview

• Implements the queue data structure using Implements the queue data structure using a doubly-linked lista doubly-linked list

• Major methods:Major methods:

• offer(object)offer(object) – adds an object to the – adds an object to the end of the queueend of the queue

• poll()poll() – removes and returns the object at – removes and returns the object at the beginning of the queuethe beginning of the queue

• peek()peek() – returns the object at the – returns the object at the beginning of the queue without removing itbeginning of the queue without removing it

Page 40: Lists, Stacks, Queues, Trees, Hash Tables Basic Data Structures.

The The LinkedListLinkedList Class – More Class – More MethodsMethods

• Other methods:Other methods:

• size()size() – gets the number of elements – gets the number of elements contained in the queuecontained in the queue

• clear()clear() – removes all elements from the – removes all elements from the queuequeue

• contains(object)contains(object) – determines whether – determines whether given element is in the queuegiven element is in the queue

• toArraytoArray()() – converts the queue to array – converts the queue to array

Page 41: Lists, Stacks, Queues, Trees, Hash Tables Basic Data Structures.

Using the Using the

LinkedListLinkedList classclass

ExamplesExamples

Page 42: Lists, Stacks, Queues, Trees, Hash Tables Basic Data Structures.

Queue –Queue – ExampleExample

• Using Using offeroffer()() and and pollpoll()() methods methods

public static void main(String[] args) {public static void main(String[] args) { Queue<String> queue = new LinkedList<String>();Queue<String> queue = new LinkedList<String>();

queue.offer("Message One");queue.offer("Message One"); queue.offer("Message Two");queue.offer("Message Two"); queue.offer("Message Three");queue.offer("Message Three"); queue.offer("Message Four");queue.offer("Message Four"); queue.offer("Message Five");queue.offer("Message Five");

while (queue.size() > 0) {while (queue.size() > 0) { String msg = queue.poll();String msg = queue.poll(); System.out.println(msg);System.out.println(msg); }}}}

Page 43: Lists, Stacks, Queues, Trees, Hash Tables Basic Data Structures.

Using the Using the

LinkedListLinkedList classclass

Live DemoLive Demo

Page 44: Lists, Stacks, Queues, Trees, Hash Tables Basic Data Structures.

Sequence N, N+1, 2*NSequence N, N+1, 2*N

• We are given the sequence:We are given the sequence:

S = N, N+1, 2*N, N+2, 2*(N+1), 2*N+1, 4*N, ...S = N, N+1, 2*N, N+2, 2*(N+1), 2*N+1, 4*N, ...

• Write a program to find the first index of Write a program to find the first index of given number Pgiven number P

• Example: N = 3, P = 16Example: N = 3, P = 16

S = 3, 4, 6, 5, 8, 7, 12, 6, 10, 9, 16, 8, 14, ...S = 3, 4, 6, 5, 8, 7, 12, 6, 10, 9, 16, 8, 14, ...

Index of P = 11Index of P = 11

+1+1+1+1

*2*2*2*2

+1+1+1+1

*2*2*2*2

+1+1+1+1

*2*2*2*2

Page 45: Lists, Stacks, Queues, Trees, Hash Tables Basic Data Structures.

Sequence – SolutionSequence – Solution

int n = 3;int n = 3;int p = 16;int p = 16;

Queue<Integer> queue = new LinkedList<Integer>();Queue<Integer> queue = new LinkedList<Integer>();queue.offer(n);queue.offer(n);

int index = 0;int index = 0;while (queue.size() > 0) {while (queue.size() > 0) { index++;index++; int current = queue.poll();int current = queue.poll(); if (current == p) {if (current == p) { System.out.println("Index = " + index);System.out.println("Index = " + index); return;return; }} queue.offer(current + 1);queue.offer(current + 1); queue.offer(2 * current);queue.offer(2 * current);}}

Page 46: Lists, Stacks, Queues, Trees, Hash Tables Basic Data Structures.

Sequence N, N+1, 2*NSequence N, N+1, 2*N

Live DemoLive Demo

Page 47: Lists, Stacks, Queues, Trees, Hash Tables Basic Data Structures.

What is Tree?What is Tree?

Definition, Types of TreesDefinition, Types of Trees

Page 48: Lists, Stacks, Queues, Trees, Hash Tables Basic Data Structures.

TreesTrees

• TerminologyTerminology

• Node, edge, root, child, children, siblings, Node, edge, root, child, children, siblings, parent, ancestor, descendant, predecessor, parent, ancestor, descendant, predecessor, successor, internal node, leaf, depth, heightsuccessor, internal node, leaf, depth, height

1717

1515141499

66 55 88

Height = 2Height = 2

Depth 0Depth 0

Depth 1Depth 1

Depth 2Depth 2

Page 49: Lists, Stacks, Queues, Trees, Hash Tables Basic Data Structures.

Binary TreesBinary Trees

• Binary trees: most used formBinary trees: most used form

• Each node has at most 2 childrenEach node has at most 2 children

1010

1717

151599

66 55 88

““right child”right child”““right child”right child”““left subtree”left subtree”““left subtree”left subtree”

““root”root”““root”root”

““left child”left child”““left child”left child”

Page 50: Lists, Stacks, Queues, Trees, Hash Tables Basic Data Structures.

Binary TreesBinary Trees TraversalsTraversals

• Traversal can be done in pre-order, in-order Traversal can be done in pre-order, in-order and post-orderand post-order

• Pre-order: left, root, right – 6, 9, 12, 17, 19, 25Pre-order: left, root, right – 6, 9, 12, 17, 19, 25• In-order: root, left, right – 17, 9, 6, 12, 19, 25In-order: root, left, right – 17, 9, 6, 12, 19, 25• Post-order: left, right, root – 6, 12, 9, 25, 19, 17Post-order: left, right, root – 6, 12, 9, 25, 19, 17

1717

191999

66 1212 2525

Page 51: Lists, Stacks, Queues, Trees, Hash Tables Basic Data Structures.

Binary Search TreesBinary Search Trees

• Binary search trees are Binary search trees are orderedordered

• A binary tree in which A binary tree in which binary-search-tree binary-search-tree propertyproperty holds: holds:• For each node For each node xx in the tree in the tree

• All the elements of the left subtree of All the elements of the left subtree of xx are are ≤≤ xx

• All the elements of the right subtree of All the elements of the right subtree of xx are > are > xx

• Binary search trees can be balancedBinary search trees can be balanced• Balanced trees has low heightBalanced trees has low height

Page 52: Lists, Stacks, Queues, Trees, Hash Tables Basic Data Structures.

Binary Search TreesBinary Search Trees

• Example of binary search treeExample of binary search tree

• If the tree is balanced, adding, searching, and If the tree is balanced, adding, searching, and deletion operations take approx. deletion operations take approx. log(log(nn) steps) steps

1717

191999

66 1212 2525

Page 53: Lists, Stacks, Queues, Trees, Hash Tables Basic Data Structures.

What is aWhat is aDictionary (Map)?Dictionary (Map)?

Page 54: Lists, Stacks, Queues, Trees, Hash Tables Basic Data Structures.

The Dictionary (Map) ADTThe Dictionary (Map) ADT

• The ADT "dictionary" maps key to valuesThe ADT "dictionary" maps key to values• Also known as "map" or "associative array"Also known as "map" or "associative array"

• Contains a set of (key, value) pairsContains a set of (key, value) pairs

• Dictionary ADT operations:Dictionary ADT operations:• ADD(key, value)ADD(key, value)

• FIND_BY_KEY(key) FIND_BY_KEY(key) value value

• DELETE(key)DELETE(key)

• Can be implemented in several waysCan be implemented in several ways• List, array, hash table, balanced tree, ...List, array, hash table, balanced tree, ...

Page 55: Lists, Stacks, Queues, Trees, Hash Tables Basic Data Structures.

What is a Hash What is a Hash Table?Table?

Page 56: Lists, Stacks, Queues, Trees, Hash Tables Basic Data Structures.

Hash TableHash Table

• A hash table is an array that holds a set of A hash table is an array that holds a set of (key, value) pairs(key, value) pairs

• The process of mapping a key to a position The process of mapping a key to a position in a table is called in a table is called hashinghashing

00 11 22 33 44 55 m-1m-1

...... ...... ...... ......TT

h(h(kk))

...... ...... ......

Page 57: Lists, Stacks, Queues, Trees, Hash Tables Basic Data Structures.

Hash Functions and HashingHash Functions and Hashing

• A hash function maps keys to positionsA hash function maps keys to positions

• It is denoted by It is denoted by hh

• The hash table has The hash table has mm slots, indexed from slots, indexed from 00 to to m-1m-1

• For any value For any value kk in the key range and some in the key range and some hash function hash function hh

h(h(kk) = i) = i

0 0 i < i < mm

00 11 22 33 44 55 m-1m-1

...... ...... ...... ......TT

h(h(kk))

...... ...... ......

Page 58: Lists, Stacks, Queues, Trees, Hash Tables Basic Data Structures.

Mapping FunctionsMapping Functions

• Perfect hashing function (PHF)Perfect hashing function (PHF)• h(k)h(k) : one-to-one mapping from each key : one-to-one mapping from each key kk to to

integers in [integers in [00,, mm-1-1]]

• The PHF maps each key to a distinct integer The PHF maps each key to a distinct integer within some manageable rangewithin some manageable range

• Finding a perfect hashing function is in most Finding a perfect hashing function is in most cases cases impossibleimpossible

• More realisticallyMore realistically• Hash functions Hash functions h(k)h(k) map map mostmost of the keys of the keys

onto unique integers, but onto unique integers, but not allnot all

Page 59: Lists, Stacks, Queues, Trees, Hash Tables Basic Data Structures.

Collisions in Hash TablesCollisions in Hash Tables

• CollisionCollision is the situation when different keys is the situation when different keys can have the same hash valuecan have the same hash value

h(kh(k11) = h(k) = h(k22) for k) for k11 ≠ k≠ k22

• When the number of When the number of collisionscollisions is sufficiently is sufficiently small, the small, the hash tableshash tables work quite well (fast) work quite well (fast)

• Several collisions resolution strategiesSeveral collisions resolution strategies• Chaining in a list, re-hashing, using the Chaining in a list, re-hashing, using the

neighboring slots (linear probing), ...neighboring slots (linear probing), ...

Page 60: Lists, Stacks, Queues, Trees, Hash Tables Basic Data Structures.

Collision Resolution - ChainingCollision Resolution - Chaining

h(h("Pesho""Pesho") = ) = 44 h(h("Lili""Lili") = ) = n-1n-1

h(h("Kiro""Kiro") = ) = 22

h("Mimi") = 1h("Mimi") = 1

h("Ivan") = 2 h("Ivan") = 2

h(h("Pesho""Pesho") = ) = 44 h(h("Lili""Lili") = ) = n-1n-1

h(h("Kiro""Kiro") = ) = 22

h("Mimi") = 1h("Mimi") = 1

h("Ivan") = 2 h("Ivan") = 2

nullnullTT

00 11 22 33 44 55 n-1n-1

nullnull ......nullnull

chainingchainingchainingchaining KiroKiro

IvanIvan

collisioncollisioncollisioncollision

nullnull

MimiMimi

nullnull

LiliLili

nullnull

PeshoPesho

nullnull

Page 61: Lists, Stacks, Queues, Trees, Hash Tables Basic Data Structures.

Using theUsing theHashHashMapMap class class

Page 62: Lists, Stacks, Queues, Trees, Hash Tables Basic Data Structures.

The The HashHashMapMap Class – Overview Class – Overview

• Implements the ADT dictionary as array Implements the ADT dictionary as array dynamically increased as neededdynamically increased as needed

• Contains a collection of key-and-value pairs Contains a collection of key-and-value pairs arranged by the hash code of the keyarranged by the hash code of the key

• Collisions are resolved by chainingCollisions are resolved by chaining

• The The HashHashMapMap class relies on class relies on

• Object.Object.hhashCode()ashCode() method for calculating method for calculating the hash codes of the elementsthe hash codes of the elements

• Object.Object.equals(equals()) method for comparing method for comparing elementselements

Page 63: Lists, Stacks, Queues, Trees, Hash Tables Basic Data Structures.

The The HashHashMapMap Class – Major Class – Major OperationsOperations

• Major operations:Major operations:

• putput(key(key, value), value) – adds an element with – adds an element with the specified key and value into the hash the specified key and value into the hash tabletable

• remove(keyremove(key)) – removes the element with the – removes the element with the specified key from the hash tablespecified key from the hash table

• get(keyget(key)) – returns element by key – returns element by key

• clear()clear() – removes all elements from the – removes all elements from the hash tablehash table

Page 64: Lists, Stacks, Queues, Trees, Hash Tables Basic Data Structures.

The The HashHashMapMap Class – More Class – More OperationsOperations

• More operations:More operations:

• size()size() – – returns the number of elementsreturns the number of elements

• ccontainsontainsKeyKey(key(key)) – – determines whether determines whether the hash table contains given keythe hash table contains given key

• ccontainsValue(value)ontainsValue(value) – – determines determines whether the hash table contains given valuewhether the hash table contains given value

• keySet(keySet()) – – returns a set of the keysreturns a set of the keys

• values()values() – – returns a collection of the valuesreturns a collection of the values

Page 65: Lists, Stacks, Queues, Trees, Hash Tables Basic Data Structures.

Using the Using the HashMapHashMap Class Class

ExamplesExamples

Page 66: Lists, Stacks, Queues, Trees, Hash Tables Basic Data Structures.

Hashtable - ExampleHashtable - Example

Map<String, Integer> studentsMarks =Map<String, Integer> studentsMarks =new HashMap<String, Integer>();new HashMap<String, Integer>();

studentsMarks.put("Ivan", 4);studentsMarks.put("Ivan", 4);studentsMarks.put("Peter", 6);studentsMarks.put("Peter", 6);studentsMarks.put("Maria", 6);studentsMarks.put("Maria", 6);studentsMarks.put("George", 5);studentsMarks.put("George", 5);

int peterMark = studentsMarks.get("Peter");int peterMark = studentsMarks.get("Peter");studentsMarks.remove("Peter");studentsMarks.remove("Peter");System.out.println("Is Peter in the hash table: "System.out.println("Is Peter in the hash table: "

+ studentsMarks.containsKey("Peter"));+ studentsMarks.containsKey("Peter"));

for (Map.Entry<String, Integer> studentMark :for (Map.Entry<String, Integer> studentMark :

studentsMarks.entrySet()) {studentsMarks.entrySet()) {

System.out.printf("%s --> %d%n",System.out.printf("%s --> %d%n",

studentMark.getKey(), studentMark.getValue());studentMark.getKey(), studentMark.getValue());

}}

Page 67: Lists, Stacks, Queues, Trees, Hash Tables Basic Data Structures.

Using the Using the HashMapHashMap Class Class

Live DemoLive Demo

Page 68: Lists, Stacks, Queues, Trees, Hash Tables Basic Data Structures.

Counting Words in a TextCounting Words in a Text

String s = "Welcome to our Java course. In this "String s = "Welcome to our Java course. In this "+ "course you will learn how to write simple "+ "course you will learn how to write simple "+ "programs in Java";+ "programs in Java";

String[] words = s.split("[ ,.]");String[] words = s.split("[ ,.]");Map<String, Integer> wordsCount =Map<String, Integer> wordsCount =

new HashMap<String, Integer>();new HashMap<String, Integer>();

for (String word : words) for (String word : words) if (!"".equalsIgnoreCase(word)) {if (!"".equalsIgnoreCase(word)) {

int count = 1;int count = 1;if (wordsCount.containsKey(word)) if (wordsCount.containsKey(word))

count += wordsCount.get(word);count += wordsCount.get(word);wordsCount.put(word, count);wordsCount.put(word, count);

}}for (String word : wordsCount.keySet())for (String word : wordsCount.keySet())

System.out.printf("%s --> %d%n", word,System.out.printf("%s --> %d%n", word,wordsCount.get(word));wordsCount.get(word));

Page 69: Lists, Stacks, Queues, Trees, Hash Tables Basic Data Structures.

Counting Words in a TextCounting Words in a Text

Live DemoLive Demo

Page 70: Lists, Stacks, Queues, Trees, Hash Tables Basic Data Structures.

SummarySummary

• ADT are defined by list of operations ADT are defined by list of operations independent of the implementationindependent of the implementation

• The basic data structures in the computer The basic data structures in the computer programming areprogramming are

• List – List – ArrayListArrayList class in Java class in Java

• Stack – Stack – StackStack class in Java class in Java

• Queue – Queue – LinkedListLinkedList class in Javaclass in Java

• Trees – can be binary, balanced, search trees, Trees – can be binary, balanced, search trees, etc.etc.

• Dictionaries – Dictionaries – HashHashMapMap class in Java class in Java

Page 71: Lists, Stacks, Queues, Trees, Hash Tables Basic Data Structures.

Basic Data StructuresBasic Data Structures

Questions?Questions?Questions?Questions?

Page 72: Lists, Stacks, Queues, Trees, Hash Tables Basic Data Structures.

ExercisesExercises

1.1. Write a program that reads from the console a Write a program that reads from the console a sequence of positive integer numbers. The sequence of positive integer numbers. The sequence ends when the number 0 is entered. sequence ends when the number 0 is entered. Calculate and print the sum and average of the Calculate and print the sum and average of the elements of the sequence. Use the elements of the sequence. Use the ArrayListArrayList class.class.

2.2. Write a method that finds the longest Write a method that finds the longest subsequence of equal numbers in given array. subsequence of equal numbers in given array. Use the Use the ArrayListArrayList class. class.

3.3. Write a program that reads N integers from the Write a program that reads N integers from the console and reverses them using a stack. Use console and reverses them using a stack. Use the the StackStack class. class.

Page 73: Lists, Stacks, Queues, Trees, Hash Tables Basic Data Structures.

Exercises (2)Exercises (2)

4.4. We are given the following sequence:We are given the following sequence:SS11 = N; = N;

SS22 = S = S11 + 1; + 1;

SS33 = 2*S = 2*S11 + 1; + 1;

SS44 = S = S11 + 2; + 2;

SS55 = S = S22 + 1; + 1;

SS66 = 2*S = 2*S22 + 1; + 1;

SS77 = S = S22 + 2; + 2;

......

Write a program to print its first 100 elements for Write a program to print its first 100 elements for given N. Use the given N. Use the LinkedListLinkedList class. class.

Example: N=2Example: N=2

Sequence: 2, 3, 5, 4, 4, 7, 5, 6, 11, 7, 5, 9, 6, ...Sequence: 2, 3, 5, 4, 4, 7, 5, 6, 11, 7, 5, 9, 6, ...

Page 74: Lists, Stacks, Queues, Trees, Hash Tables Basic Data Structures.

Exercises (3)Exercises (3)

5.5. Write a program that reads a sequence of Write a program that reads a sequence of integers ending with 0 and sorts them in an integers ending with 0 and sorts them in an increasing order. Use the increasing order. Use the ArrayListArrayList class. class.

6.6. Write a program that finds in a given array of Write a program that finds in a given array of integers how many times each of them integers how many times each of them presents. Use presents. Use HashHashMapMap and and ArrayListArrayList..

Example: array = {3, 4, 4, 2, 3, 3, 4, 3, 2}Example: array = {3, 4, 4, 2, 3, 3, 4, 3, 2}

2 2 2 times 2 times

3 3 4 times 4 times

4 4 3 times 3 times

Page 75: Lists, Stacks, Queues, Trees, Hash Tables Basic Data Structures.

Exercises (4)Exercises (4)

7.7. Write a program that removes from a given Write a program that removes from a given sequence all negative numbers.sequence all negative numbers.

8.8. Write a program that removes from a given Write a program that removes from a given sequence all the numbers that present in it sequence all the numbers that present in it odd number of times. Example:odd number of times. Example:

{4, 2, 2, 5, 2, 3, 2, 3, 1, 5, 2} {4, 2, 2, 5, 2, 3, 2, 3, 1, 5, 2} {5, 3, 3, 5} {5, 3, 3, 5}

9.9. By definition the majorant of an array is a By definition the majorant of an array is a value that occur in the least half of the value that occur in the least half of the elements of the array. Write a program to find elements of the array. Write a program to find the majorant of given array (if any). Example:the majorant of given array (if any). Example:

{2, 2, 3, 3, 2, 3, 4, 3, 3} {2, 2, 3, 3, 2, 3, 4, 3, 3} 3 3

Page 76: Lists, Stacks, Queues, Trees, Hash Tables Basic Data Structures.

Exercises (7)Exercises (7)

10.10. Write a program that counts how many times Write a program that counts how many times each word from a given text presents in it. The each word from a given text presents in it. The casing differences should be ignored. The casing differences should be ignored. The result words should be ordered by their result words should be ordered by their number of occurrences in the text. Example:number of occurrences in the text. Example:

is is 2 2

the the 2 2

this this 3 3

text text 6 6

This is the TEXT. Text, text, text – THIS TEXT!This is the TEXT. Text, text, text – THIS TEXT!Is this the text?Is this the text?

Page 77: Lists, Stacks, Queues, Trees, Hash Tables Basic Data Structures.

Exercises (5)Exercises (5)

11.11. We are given numbers N and M and the We are given numbers N and M and the following operations:following operations:

a)a) N = N+1N = N+1

b)b) N = N+2N = N+2

c)c) N = N*2N = N*2

Write a program that finds the shortest Write a program that finds the shortest sequence of operations from the list above sequence of operations from the list above that starts from N and finishes in Mthat starts from N and finishes in M

• Example: N = 5, M = 16Example: N = 5, M = 16

• Sequence: 5 Sequence: 5 7 7 8 8 16 16

Page 78: Lists, Stacks, Queues, Trees, Hash Tables Basic Data Structures.

Exercises (6)Exercises (6)

12.12. We are given a labyrinth of size N x N. Some of We are given a labyrinth of size N x N. Some of its cells are empty (0) and some are full (x). We its cells are empty (0) and some are full (x). We can move from an empty cell to another empty can move from an empty cell to another empty cell if they share common wall. Given a cell if they share common wall. Given a starting position (*) calculate and fill in the starting position (*) calculate and fill in the array the minimal distance from this position array the minimal distance from this position to any other cell in the array. Use "u" for the to any other cell in the array. Use "u" for the unreachable cells. Example:unreachable cells. Example:

00 00 00 xx 00 xx00 xx 00 xx 00 xx00 ** xx 00 xx 0000 xx 00 00 00 0000 00 00 xx xx 0000 00 00 xx 00 xx

33 44 55 xx uu xx22 xx 66 xx uu xx11 ** xx 88 xx 101022 xx 66 77 88 9933 44 55 xx xx 101044 55 66 xx uu xx