Data Structure - Department of Computer Engineering, Chulalongkorn

18
Data Structure Data Structure Basic Data Structure Basic Data Structure Scalar Data Structure Scalar Data Structure Integer, Character, Boolean, Float, Double, Integer, Character, Boolean, Float, Double, etc. etc. Vector or Linear Data Structure Vector or Linear Data Structure Array, List, Queue, Stack, Priority Queue, Set, Array, List, Queue, Stack, Priority Queue, Set, etc. etc. Non Non- linear Data Structure linear Data Structure Tree, Table, Graph, Hash Table, etc. Tree, Table, Graph, Hash Table, etc.

Transcript of Data Structure - Department of Computer Engineering, Chulalongkorn

1

Data StructureData Structure

Basic Data StructureBasic Data Structure

Scalar Data StructureScalar Data Structure–– Integer, Character, Boolean, Float, Double, Integer, Character, Boolean, Float, Double,

etc.etc.Vector or Linear Data StructureVector or Linear Data Structure–– Array, List, Queue, Stack, Priority Queue, Set, Array, List, Queue, Stack, Priority Queue, Set,

etc. etc. NonNon--linear Data Structurelinear Data Structure–– Tree, Table, Graph, Hash Table, etc.Tree, Table, Graph, Hash Table, etc.

2

Scalar Data StructureScalar Data Structure

A A scalarscalar isis thethe simplestsimplest kindkind ofof datadata thatthat Java Java programming languageprogramming language manipulatesmanipulates.. A A scalarscalar isiseithereither a a numbernumber ((likelike 44 oror 3.253.25ee20)20) oror a a charactercharacter. . ((Integer, Character, Boolean, Float, Integer, Character, Boolean, Float, Double, etc.)Double, etc.)A A scalarscalar valuevalue cancan bebe actedacted uponupon withwith operatorsoperators((likelike plusplus oror concatenateconcatenate),), generallygenerally yieldingyielding a a scalarscalar resultresult.. A A scalarscalar valuevalue cancan bebe storedstored intointo a a scalarscalar variablevariable.. ScalarsScalars cancan bebe readread fromfrom filesfilesandand devicesdevices andand writtenwritten outout asas wellwell..

List List –– A Basic Data StructureA Basic Data StructureBy definition, a By definition, a listlist is a finite is a finite setset of entries with a of entries with a certain order. certain order. The entries in the list, depending on the The entries in the list, depending on the language, may be constrained to the same language, may be constrained to the same typetype. . An An arrayarray is a related data structure that also is a related data structure that also stores its entries sequentially. However, the stores its entries sequentially. However, the items in an array usually must be of the same items in an array usually must be of the same type. type. Nearly all kinds of Nearly all kinds of tree structurestree structures can also be can also be stored as listsstored as lists

3

Queue / Stack as Basic Data Queue / Stack as Basic Data StructuresStructures

Queue is a list with FirstQueue is a list with First--In FistIn Fist--Out manipulationOut manipulationEnQueueEnQueue (Insert queue)(Insert queue)DeQueueDeQueue (Delete queue)(Delete queue)

Stack is a list with LastStack is a list with Last--In FirstIn First--Out manipulationOut manipulationPush (Insert stack)Push (Insert stack)Pop (Delete stack)Pop (Delete stack)

ObjectObject--Oriented ConceptOriented Concept

Everything is objectEverything is objectClass (Class object)Class (Class object)Instance (Instance object)Instance (Instance object)ClassClass–– Encapsulation (Information Hiding, Data, Methods)Encapsulation (Information Hiding, Data, Methods)–– Polymorphism (Overriding, Overloading)Polymorphism (Overriding, Overloading)–– Visibility Mode (public, protected, private)Visibility Mode (public, protected, private)

Association Association –– Composition / AggregationComposition / Aggregation

4

Separating Collection Interfaces Separating Collection Interfaces and Implementationand Implementation

AsAs isis commoncommon forfor modernmodern datadata structurestructurelibrarieslibraries,, thethe JavaJava collectioncollection librarylibraryseparatesseparates interfacesinterfaces andand implementationsimplementations..LetLet usus looklook atat thatthat separationseparation withwith a a familiarfamiliar datadata structurestructure,, thethe queuequeue..TheThe JavaJava librarylibrary doesdoes notnot supplysupply a a queuequeue,,butbut itit isis neverthelessnevertheless a a goodgood exampleexample totointroduceintroduce thethe basicbasic conceptsconcepts..

Queue InterfaceQueue InterfaceA A queuequeue interfaceinterface specifiesspecifies thatthat youyou cancan addadd elementselementsatat thethe tailtail endend ofof thethe queuequeue,, removeremove themthem atat thethe headhead,,andand findfind outout howhow manymany elementselements areare inin thethe queuequeue.. YouYouuseuse a a queuequeue whenwhen youyou needneed toto collectcollect objectsobjects andandretrieveretrieve themthem inin a a ""firstfirst inin,, firstfirst outout"" fashionfashion..

interfaceinterface QueueQueue{{ voidvoid addadd((ObjectObject objobj););ObjectObject removeremove();();intint sizesize();();

}}

5

Implementation of Queue InterfaceImplementation of Queue InterfaceTheThe interfaceinterface tellstells youyou nothingnothing aboutabout howhow thethe queuequeue isisimplementedimplemented.. ThereThere areare twotwo commoncommon implementationsimplementations ofof a a queuequeue,,oneone thatthat usesuses a a ""circularcircular arrayarray"" andand oneone thatthat usesuses a a linkedlinked listlist

Implementation of Queue Interface Implementation of Queue Interface -- CodeCode

class CircularArrayQueue implements Queue{ CircularArrayQueue( int capacity) { . . . } publicvoid add(Object obj) { . . . }public Object remove() { . . . }public int size ( ) { . . . }private Object [ ] elements;private int head;private int tail;}

Queue expressLane = newCircularArrayQueue(100);expressLane.add(new Customer("Harry"));

class LinkedListQueueimplements Queue{ LinkedListQueue() { . . . }public void add(Object obj) { . . . }public Object remove() { . . . }public int size() { . . . }private Link head;private Link tail;}

Queue expressLane = newLinkedListQueue(); expressLane.add(new Customer("Harry"));

1

2

class CircularArrayQueue{ public void add(Object obj)throws CollectionFullException. . .

}

6

CollectionsCollections

A collection (sometimes called a A collection (sometimes called a containercontainer) is an ) is an object that groups multiple elements into a object that groups multiple elements into a single unit. single unit. Collections are used to store, retrieve and Collections are used to store, retrieve and manipulate data, and to transmit data from one manipulate data, and to transmit data from one method to another.method to another.Collections typically represent data items that Collections typically represent data items that form a natural group, a card hand, a mail folder, form a natural group, a card hand, a mail folder, a telephone directorya telephone directory……

The Java Collections The Java Collections FrameworkFramework

The Java collections framework is made up of a The Java collections framework is made up of a set of interfaces and classes for working with set of interfaces and classes for working with groups of objectsgroups of objectsThe Java Collections Framework providesThe Java Collections Framework provides–– InterfacesInterfaces: abstract data types representing : abstract data types representing

collections. collections. ImplementationsImplementations: concrete : concrete implementations of the collection interfaces. implementations of the collection interfaces.

–– AlgorithmsAlgorithms: methods that perform useful : methods that perform useful computations, like searching and sorting, on objects computations, like searching and sorting, on objects that implement collection interfaces.that implement collection interfaces.

7

The InterfacesThe Interfaces

Note: Some of the material on these slides was taken from the Java Tutorial at http://www.java.sun.com/docs/books/tutorial

SetsSetsA group of unique items, meaning that the group A group of unique items, meaning that the group contains no duplicatescontains no duplicatesSome examplesSome examples–– The set of uppercase letters The set of uppercase letters ‘‘AA’’ through through ‘‘ZZ’’–– The set of nonnegative integers { 0, 1, 2, The set of nonnegative integers { 0, 1, 2, …… }}–– The empty set {}The empty set {}

The basic properties of setsThe basic properties of sets–– Contain only one instance of each itemContain only one instance of each item–– May be finite or infiniteMay be finite or infinite–– Can define abstract conceptsCan define abstract concepts

8

MapsMaps

A map is a special kind of set.A map is a special kind of set.A map is a set of pairs, each pair representing a A map is a set of pairs, each pair representing a oneone--directional directional ““mappingmapping”” from one set to from one set to anotheranother–– An object that maps keys to valuesAn object that maps keys to values

Some examplesSome examples–– A map of keys to database recordsA map of keys to database records–– A dictionary (words mapped to meanings)A dictionary (words mapped to meanings)–– The conversion from base 2 to base 10The conversion from base 2 to base 10

What Is The Real Difference?What Is The Real Difference?

CollectionsCollections–– You can add, remove, lookup You can add, remove, lookup isolatedisolated items in items in

the collectionthe collectionMapsMaps–– The collection operations are available but The collection operations are available but

they work with a they work with a keykey--valuevalue pair instead of an pair instead of an isolated elementisolated element

–– The typical use of a The typical use of a MapMap is to provide access is to provide access to values stored by keyto values stored by key

9

Another Way to Look At ItAnother Way to Look At It

The The CollectionCollection interface is a group of interface is a group of objects, with duplicates allowedobjects, with duplicates allowedSetSet extends extends CollectionCollection but forbids but forbids duplicatesduplicatesListList extends extends CollectionCollection and allows and allows duplicates and positional indexingduplicates and positional indexingMapMap extends neither extends neither SetSet nor nor CollectionCollection

The The CollectionCollection InterfaceInterface

Found in the java.utilpackage

Optional methods throwUnsupportedOperationExceptionif the implementing class doesnot support the operation.

Bulk operations performsome operation on an entireCollection in a single shot

The toArray methods allow the contentsof a Collection to be translated intoAn array.

// Basic Operationssize():int; isEmpty():boolean; contains(Object):boolean; add(Object):boolean; // Optional remove(Object):boolean; // Optionaliterator():Iterator;

// Bulk Operations containsAll(Collection):boolean; addAll(Collection):boolean; // OptionalremoveAll(Collection):boolean;// Optional retainAll(Collecton):boolean; // Optional clear():void; // Optional

// Array Operations toArray():Object[]; toArray(Object[]):Object[];

Collection

10

SetSet InterfaceInterface

A A SetSet is a is a CollectionCollection that cannot contain that cannot contain duplicate elements. duplicate elements. –– SetSet models the mathematical models the mathematical setset abstraction. abstraction.

The The SetSet interface extends interface extends CollectionCollection and and contains contains nono methods other than those inherited methods other than those inherited from from CollectionCollectionIt adds the restriction that duplicate elements are It adds the restriction that duplicate elements are prohibited. prohibited. Two Two SetSet objects are equal if they contain the objects are equal if they contain the same elements. same elements.

SetSet Bulk OperationsBulk Operations

The bulk operations perform standard setThe bulk operations perform standard set--algebraic operations. Suppose algebraic operations. Suppose s1s1 and and s2s2 are are SetsSets..–– s1.containsAll(s2)s1.containsAll(s2): Returns : Returns truetrue if if s2s2 is a is a subsetsubset of of

s1s1. . –– s1.addAll(s2)s1.addAll(s2): Transforms : Transforms s1s1 into the into the unionunion of of s1s1 and and

s2s2. (The union of two sets is the set containing all the . (The union of two sets is the set containing all the elements contained in either set.)elements contained in either set.)

–– s1.retainAll(s2)s1.retainAll(s2): Transforms : Transforms s1s1 into the into the intersectionintersectionof of s1s1 and and s2s2. (The intersection of two sets is the set . (The intersection of two sets is the set containing only the elements that are common in both containing only the elements that are common in both sets.) sets.)

11

Java Java ListsLists

A A ListList is an ordered is an ordered CollectionCollection (sometimes (sometimes called a called a sequencesequence). ). Lists may contain duplicate elements. Lists may contain duplicate elements. In addition to the operations inherited from In addition to the operations inherited from CollectionCollection, the , the ListList interface includes interface includes operations for: operations for: –– Positional AccessPositional Access–– SearchSearch–– List IterationList Iteration–– RangeRange--viewview

ListList InterfaceInterface

Think of the Vectorclass

// Positional Access get(int):Object; set(int,Object):Object; // Optionaladd(int, Object):void; // Optionalremove(int index):Object; // Optional addAll(int, Collection):boolean; // Optional

// Search int indexOf(Object); int lastIndexOf(Object);

// Iteration listIterator():ListIterator; listIterator(int):ListIterator;

// Range-view List subList(int, int):List;

List

12

MapMap InterfaceInterface

// Basic Operations put(Object, Object):Object; get(Object):Object; remove(Object):Object; containsKey(Object):boolean; containsValue(Object):boolean; size():int; isEmpty():boolean;

// Bulk Operations void putAll(Map t):void; void clear():void;

// Collection Views keySet():Set; values():Collection; entrySet():Set;

Map

getKey():Object; getValue():Object; setValue(Object):Object;

EntrySet

Implementation ClassesImplementation Classes

HashTableHashTablePropertiesProperties

TreeMapTreeMapHashMapHashMapMapMap

VectorVectorStackStack

LinkedListLinkedListArrayListArrayListListList

TreeSetTreeSetHashSetHashSetSetSet

HistoricalHistoricalImplementationImplementationInterfaceInterface

Note: When writing programs think about interfaces and not implementations. This way the program does not become dependent on any added methods in a given implementation, leaving the programmer with the freedom to change implementations.

13

1.01.0ttCopyright Copyright ฉฉ 1998 1998 Purple Technology, Purple Technology,

Inc.Inc. 2525

IteratorIterator

Represents a loopRepresents a loopCreated by CollectionCreated by Collection..iteratoriterator()()Similar to EnumerationSimilar to Enumeration–– Improved method namesImproved method names–– Allows a removeAllows a remove() () operation on the current operation on the current

itemitem

1.01.0ttCopyright Copyright ฉฉ 1998 1998 Purple Technology, Purple Technology,

Inc.Inc. 2626

IteratorIterator MethodsMethods

booleanboolean hasNexthasNext()()–– Returns Returns truetrue if the iteration has more if the iteration has more

elementselements

Object nextObject next()()–– Returns next element in the iterationReturns next element in the iteration

void removevoid remove()()–– Removes the current element from the Removes the current element from the

underlying Collectionunderlying Collection

14

IteratorIterator

An object that An object that implements the implements the IteratorIterator interface interface generates a series of generates a series of elements, one at a timeelements, one at a time–– Successive calls to the Successive calls to the next()next() mmethod return ethod return successive elements of the successive elements of the series. series.

The The remove()remove() method method removes from the removes from the underlying underlying CollectionCollection the the last element that was last element that was returned by returned by nextnext..

hasNext():boolean; next():Object; remove():voidt;

Iterator

IteratorIterator as pointeras pointerIterator iter = c.iterator();while (iter.hasNext()){ Object obj = iter.next();do something with obj}

Iterator it = c.iterator();it.next(); // skip over the

//first elementit.remove(); // now remove it

Remove

Traverse

it.remove();it.remove(); // Error!

it.remove();it.next();it.remove(); // Ok

public static void print(Collection c){ System.out.print("[ ");Iterator iter = c.iterator();while (iter.hasNext())

System.out.print( iter.next() + " ");System.out.println("]");}

15

Implementation of method Implementation of method ‘‘addAlladdAll’’

public static boolean addAll( Collection to, Collection from){ Iterator iter = from.iterator();boolean modified = false;while (iter.hasNext())

if (to.add(iter.next()))modified = true;

return modified;}

int size();boolean isEmpty();boolean contains(Object obj);boolean containsAll(Collection c);boolean equals(Object other);boolean addAll(Collection from);boolean remove(Object obj);boolean removeAll(Collection c);void clear();boolean retainAll(Collection c);Object[ ] toArray();

LinkLink--ListedListed

Remove a Element

16

ListIteratorListIterator is extended from is extended from IteratorIterator

LinkedList staff = new LinkedList();staff.add("Angela");staff.add("Bob");staff.add("Carl");Iterator iter = staff.iterator();for (int i = 0; i < 3; i++)

System.out.println(iter.next());iter.remove(); // remove last visited element

interface ListIterator extends Iterator{ void add(Object);. . . }

1.01.0ttCopyright Copyright ฉฉ 1998 1998 Purple Technology, Purple Technology,

Inc.Inc. 3232

ListIteratorListIterator

interface interface ListIteratorListIterator extends extends IteratorIteratorCreated by ListCreated by List..listIteratorlistIterator() () Adds methods to Adds methods to –– traverse the List in either directiontraverse the List in either direction–– modify the List during iterationmodify the List during iteration

Methods addedMethods added::–– hasPrevioushasPrevious()(), previous, previous()()–– nextIndexnextIndex()(), , previousIndexpreviousIndex()()–– setset((ObjectObject)), add, add((ObjectObject))

17

Using Using ListIteratorListIterator to Add an to Add an ElementElement

ListIterator iter = staff.listIterator();iter.next();iter.add("Juliet");

ListIterator iter = list.listIterator();Object oldValue = iter.next(); // returns first elementiter.set(newValue); // sets first element to newValue

LinkedList list = . . .;ListIterator iter1 = list.listIterator();ListIterator iter2 = list.listIterator();iter1.next();iter1.remove();iter2.next(); // throws ConcurrentModificationException

18

LinkedListTest.javaLinkedListTest.javaimport java.util.*;

public class LinkedListTest{ public static void main( String[] args){

List a = new LinkedList();a.add("Angela");a.add("Carl");a.add("Erica");

List b = new LinkedList();b.add("Bob");b.add("Doug");b.add("Frances");b.add("Gloria"); // merge the words from b into a

ListIterator aIter = a.listIterator();Iterator bIter = b.iterator();

while (bIter.hasNext()){

if (aIter.hasNext()) aIter.next();aIter.add(bIter.next());

}

System.out.println(a); // remove every second wordfrom b

bIter = b.iterator();while (bIter.hasNext()){

bIter.next(); // skip one elementif (bIter.hasNext()){

bIter.next(); // skip next elementbIter.remove(); // remove that element

} }

System.out.println(b); // bulk operation: remove allwords in b from a

a.removeAll(b);System.out.println(a);

} }