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.
18
Embed
Data Structure - Department of Computer Engineering, Chulalongkorn
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
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)
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;}
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.
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
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.
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
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())
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 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