SlideShare a Scribd company logo
Lists, Stacks, Queues, Trees, Hash Tables Basic Data Structures
Contents Abstract Data Types (ADT) Lists –  ArrayList  Class Stacks –  Stack  Class Queues –  Queue  Class Trees – Terminology and Types Dictionaries –  HashMap  Class
Abstract Data Types An Abstract Data Type (ADT) is a data type together with the operations, whose properties are specified independently of any particular implementation ADT are set of definitions of operations (like the interfaces in Java) Can have several different implementations Different implementations can have different efficiency
Basic Data Structures Linear structures Lists: Variable-size Stacks: LIFO (last in first out) structure Queues: FIFO (first in first out) structure Trees Dictionaries (maps) Contain pairs (key, value) Hash tables: Unordered lists which use a ‘hash function’ to insert and search
What Is a List?
The List ADT List is linear data structure (container) that contains a sequence of elements (objects) Has variable size Objects are arranged linearly Can be implemented in several ways Statically (using array) Dynamically (linked implementation) Using the  ArrayList  class
Static and Linked Lists
Static List Implemented by an array Provide direct access by index Usually has limited capacity Resizing is slow operation Slow insert and deletion 0 1 2 3 4 5 6 7 8 11 7 18 14 L 5 2 33 47 3
Linked List Dynamic (pointer-based) implementation Different forms Singly-linked and doubly-linked Sorted and Unsorted Singly-linked List - each “Object” has “ value ” and “ next ” fields 11 next 7 next 18 next 14 next head null
Linked List (2) Doubly-linked List - each “Object” has “ value ”, “ next ” and “ prev ” fields 11 next prev head tail 7 next prev 18 next prev 14 next prev null null
Using the ArrayList   class
The  java.util.ArrayList  Class Implements the list data structure using an array whose size is dynamically increased as needed Allocates in advance buffer space for new elements (for better performance) Insertion methods: add(Object)  – adds an object at the end add (index ,   Object)  – inserts an object to the list at a specified position size()  – returns the number of elements
The  ArrayList  Class Deletion methods: remove(Object)  – removes the first occurrence of a specific object remove( index)  – removes the element at the specified position clear()  – removes all elements Other supported methods: c ontains() ,   t oArray()
The  ArrayList  Class(2) ArrayList  can contain any data type Elements are added directly Typecasting is required when extracting elements unless we use Generics Converting to array List list = new ArrayList(); list. a dd(5); // Add integer value list. a dd("some string"); // Add string value int firstElement = ((Integer)(list.get(0))).intValue(); String secondElement = (String)list.get(1);  Integer[] arr = list.toArray(new Integer[list.size()]);
What are Generics Generics are classes or interfaces that can be instantiated with a variety of types They have 1 or more formal type parameters When using a generic you specify an actual type List<String> list = new ArrayList<String>(); String s = new String(&quot; li1 &quot;); list.add(s); list.add(5); // This will cause compile time error Specifies that String is actual type of this  List 5 is not a String
Primes[n..m] – Example Find all prime numbers in a specified interval public static ArrayList<Integer>   getPrimes(int start, int end) { List<Integer> primesList =    new ArrayList<Integer>(); for (int num = start; num <= end; num++) { boolean prime = true; for (int div = 2; div <= Math.sqrt(num); div++) { if (num % div == 0) { prime = false; break; } } if (prime) { primesList.add(num); } } return primesList; }
Primes[n..m] Live Demo
Union and Intersection of Lists – Example public static Integer[] union(Integer[] firstArr, Integer[] secondArr) { List<Integer> union = new ArrayList<Integer>(); for (Integer item : firstArr) { union.add(item); } for (Integer item : secondArr) { if (!union.contains(item)) { union.add(item); } } return union.toArray(new Integer[union.size()]); } //Example continues...
Union and Intersection of Lists – Example(2) public static Integer[] intersect(Integer[] firstArr, Integer[] secondArr) { List<Integer> intersect = new ArrayList<Integer>(); for (Integer item : firstArr) { if (Arrays.binarySearch(secondArr, item) >= 0) { intersect.add(item); } } return intersect.toArray( new Integer[intersect.size()]); }
Union and Intersection Live Demo
What is a Stack?
The Stack ADT LIFO (last in first out) structure Elements inserted (push) at “top” Elements removed (pop) from “top” Can be implemented in several ways Statically (using array) Dynamically (linked implementation) Using the  Stack  class
Static Stack Array-based (static) implementation Usually has limited capacity Has  top  variable, pointing to the top IsEMPTY( S ) Check if  S.top  = -1 0 1 2 3 4 5 6 7 8 11 7 18 14 S top
Linked Stack Dynamic (pointer-based) implementation Each “object” has “value” and “next” fields Dynamically create and delete objects 11 next 7 next 18 next 14 next top null
Using the  Stack  class
The  Stack  Class – Overview Implements the stack data structure using an array whose size is dynamically increased as needed Major methods: push(object)  – inserts elements to the stack pop()  – removes and returns the top element from the stack peek()  – returns the top element of the stack without removing it
The  Stack  Class – More Methods Other methods: size()  – returns the number of elements clear()  – removes all elements contains(object)  – determines whether given element is in the stack toArray()  – converts the stack to array
Examples Using the  Stack  class
Stack  – Example Using  push() ,  pop()  and  peek()  methods public static void main(String[] args) { Stack<String> stack = new Stack<String>(); stack.push(&quot;1. Ivan&quot;); stack.push(&quot;2. Nikolay&quot;); stack.push(&quot;3. Maria&quot;); stack.push(&quot;4. George&quot;); System.out.println(&quot;Top = &quot; + stack.peek()); while (stack.size() > 0)   { String personName = stack.pop(); System.out.println(personName); } }
Live Demo Using the  Stack  class
Matching Brackets – Example We are given an arithmetical expression with brackets that can be nested. We want to extract all parts of the expression that are closed in brackets. Example: 1 + (3 + 2 - (2+3) * 4 - ((3+1)*(4-2))) Result: (2+3) (3+1) (4-2) ((3+1)*(4-2)) (3 + 2 - (2+3) * 4 - ((3+1)*(4-2)))
Matching Brackets – Solution with a Stack String expression = &quot;1 + (3 + 2 - (2+3) * 4 - ((3+1)*(4-2)))&quot;; Stack<Integer> stack = new Stack<Integer>(); for (int i = 0; i < expression.length(); i++) { char ch = expression.charAt(i); if (ch == '(') { stack.push(i); } else if (ch == ')') { int startIndex = (int) stack.pop(); String contents =  expression.substring(startIndex, i + 1); System.out.println(contents); } }
Live Demo Matching Brackets
What is a Queue?
The Queue ADT FIFO (first in first out) structure Elements inserted at tail (enqueue) Elements removed from head ( dequeue ) Useful in many situations Processing jobs, print queues, messages Can be implemented in several ways Statically (using array) Dynamically (using pointers) Using the  LinkedList  class
Static Queue Static (array-based) implementation Queue has limited (fixed) capacity Implement as a “circular array” Maintain  Q.Capacity  and  Q.Length Has  head  and  tail  variables, pointing to the head and the tail 0 1 2 3 4 5 6 7 8 11 7 18 14 Q head tail
Linked Queue Dynamic (pointer-based) implementation Each “object” has “ value ” and “ next ” fields Dynamically create and delete objects 11 next 7 next 18 next 14 next head tail null
Using the  LinkedList  class
The  LinkedList  Class – Overview Implements the queue data structure using a doubly-linked list Major methods: offer(object)  – adds an object to the end of the queue poll()  – removes and returns the object at the beginning of the queue peek()  – returns the object at the beginning of the queue without removing it
The  LinkedList  Class – More Methods Other methods: size()  – gets the number of elements contained in the queue clear()  – removes all elements from the queue contains(object)  – determines whether given element is in the queue toArray ()  – converts the queue to array
Examples Using the  LinkedList   class
Queue –   Example Using  offer ()  and  poll ()  methods public static void main(String[] args) { Queue<String> queue = new LinkedList<String>(); queue.offer(&quot;Message One&quot;); queue.offer(&quot;Message Two&quot;); queue.offer(&quot;Message Three&quot;); queue.offer(&quot;Message Four&quot;); queue.offer(&quot;Message Five&quot;); while (queue.size() > 0) { String msg = queue.poll(); System.out.println(msg); } }
Live Demo Using the  LinkedList   class
Sequence N, N+1, 2*N We are given the sequence: 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 given number P Example: N = 3, P = 16 S = 3, 4, 6, 5, 8, 7, 12, 6, 10, 9, 16, 8, 14, ... Index of P = 11 +1 *2 +1 *2 +1 *2
Sequence – Solution int n = 3; int p = 16; Queue<Integer> queue = new LinkedList<Integer>(); queue.offer(n); int index = 0; while (queue.size() > 0) { index++; int current = queue.poll(); if (current == p) { System.out.println(&quot;Index = &quot; + index); return; } queue.offer(current + 1); queue.offer(2 * current); }
Live Demo Sequence N, N+1, 2*N
Definition, Types of Trees What is Tree?
Trees Terminology Node, edge, root, child, children, siblings, parent, ancestor, descendant, predecessor, successor, internal node, leaf, depth, height 17 15 14 9 6 5 8 Height = 2 Depth 0 Depth 1 Depth 2
Binary Trees Binary trees: most used form Each node has at most 2 children 10 17 15 9 6 5 8 “ right child” “ left subtree” “ root” “ left child”
Binary Trees   Traversals Traversal can be done in pre-order, in-order and post-order Pre-order: left, root, right –  6, 9, 12, 17, 19, 25 In-order: root, left, right – 17, 9, 6, 12, 19, 25 Post-order: left, right, root – 6, 12, 9, 25, 19, 17 17 19 9 6 12 25
Binary Search Trees Binary search trees are  ordered A binary tree in which  binary-search-tree property  holds: For each node  x  in the tree All the elements of the left subtree of  x  are  ≤   x All the elements of the right subtree of  x  are >  x Binary search trees can be balanced Balanced trees has low height
Binary Search Trees Example of binary search tree If the tree is balanced, adding, searching, and deletion operations take approx.  log( n ) steps 17 19 9 6 12 25
What is a Dictionary (Map)?
The Dictionary (Map) ADT The ADT &quot;dictionary&quot; maps key to values Also known as &quot;map&quot; or &quot;associative array&quot; Contains a set of (key, value) pairs Dictionary ADT operations: ADD(key, value) FIND_BY_KEY(key)    value DELETE(key) Can be implemented in several ways List, array, hash table, balanced tree, ...
What is a Hash Table?
Hash Table A hash table is an array that holds a set of (key, value) pairs The process of mapping a key to a position in a table is called  hashing 0 1 2 3 4 5 m-1 ... ... ... ... T h( k ) ... ... ...
Hash Functions and Hashing A hash function maps keys to positions It is denoted by  h The hash table has  m  slots, indexed from  0  to  m-1 For any value  k  in the key range and some hash function  h h( k ) = i 0    i <  m 0 1 2 3 4 5 m-1 ... ... ... ... T h( k ) ... ... ...
Mapping Functions Perfect hashing function (PHF) h(k)  : one-to-one mapping from each key  k  to integers in [ 0 ,   m -1 ] The PHF maps each key to a distinct integer within some manageable range Finding a perfect hashing function is in most cases  impossible More realistically Hash functions  h(k)  map  most  of the keys onto unique integers, but  not all
Collisions in Hash Tables Collision  is the situation when different keys can have the same hash value h(k 1 ) = h(k 2 ) for k 1   ≠ k 2 When the number of  collisions  is sufficiently small, the  hash tables  work quite well (fast) Several collisions resolution strategies Chaining in a list, re-hashing, using the neighboring slots (linear probing), ...
Collision Resolution - Chaining   h( &quot;Pesho&quot; ) =  4 h( &quot;Lili&quot; ) =  n-1 h( &quot;Kiro&quot; ) =  2   h(&quot;Mimi&quot;) = 1 h(&quot;Ivan&quot;) = 2    null T 0 1 2 3 4 5 n-1 null ... null chaining Kiro Ivan collision null Mimi null Lili null Pesho null
Using the Hash Map  class
The  Hash Map  Class – Overview Implements the ADT dictionary as array dynamically increased as needed Contains a collection of key-and-value pairs arranged by the hash code of the key Collisions are resolved by chaining The  Hash Map  class relies on Object. h ashCode()  method for calculating the hash codes of the elements Object. equals( )  method for comparing elements
The  Hash Map  Class – Major Operations Major operations: put (key , value)  – adds an element with the specified key and value into the hash table remove(key )  – removes the element with the specified key from the hash table get(key )  – returns element by key clear()  – removes all elements from the hash table
The  Hash Map  Class – More Operations More operations: size()  –  returns the number of elements c ontains Key (key )  –  determines whether the hash table contains given key c ontainsValue(value)  –  determines whether the hash table contains given value keySet( )  –  returns a set of the keys values()  –  returns a collection of the values
Examples Using the  HashMap  Class
Hashtable - Example Map<String, Integer> studentsMarks = new HashMap<String, Integer>(); studentsMarks.put(&quot;Ivan&quot;, 4); studentsMarks.put(&quot;Peter&quot;, 6); studentsMarks.put(&quot;Maria&quot;, 6); studentsMarks.put(&quot;George&quot;, 5); int peterMark = studentsMarks.get(&quot;Peter&quot;); studentsMarks.remove(&quot;Peter&quot;); System.out.println(&quot;Is Peter in the hash table: &quot; + studentsMarks.containsKey(&quot;Peter&quot;)); for (Map.Entry<String, Integer> studentMark : studentsMarks.entrySet()) { System.out.printf(&quot;%s --> %d%n&quot;, studentMark.getKey(), studentMark.getValue()); }
Live Demo Using the  HashMap  Class
Counting Words in a Text String s = &quot;Welcome to our Java course. In this &quot; + &quot;course you will learn how to write simple &quot; + &quot;programs in Java&quot;; String[] words = s.split(&quot;[ ,.]&quot;); Map<String, Integer> wordsCount = new HashMap<String, Integer>(); for (String word : words)  if (!&quot;&quot;.equalsIgnoreCase(word)) { int count = 1; if (wordsCount.containsKey(word))  count += wordsCount.get(word); wordsCount.put(word, count); } for (String word : wordsCount.keySet()) System.out.printf(&quot;%s --> %d%n&quot;, word, wordsCount.get(word));
Live Demo Counting Words in a Text
Summary ADT are defined by list of operations independent of the implementation The basic data structures in the computer programming are List –  ArrayList  class in Java Stack –  Stack  class in Java Queue –  LinkedList   class in Java Trees – can be binary, balanced, search trees, etc. Dictionaries –  Hash Map  class in Java
Basic Data Structures Questions?
Exercises Write a program that reads from the console a sequence of positive integer numbers. The sequence ends when the number 0 is entered. Calculate and print the sum and average of the elements of the sequence. Use the  ArrayList  class. Write a method that finds the longest subsequence of equal numbers in given array. Use the  ArrayList  class. Write a program that reads N integers from the console and reverses them using a stack. Use the  Stack  class.
Exercises (2) We are given the following sequence: S 1  = N; S 2  = S 1  + 1; S 3  = 2*S 1  + 1; S 4  = S 1  + 2; S 5  = S 2  + 1; S 6  = 2*S 2  + 1; S 7  = S 2  + 2; ... Write a program to print its first 100 elements for given N. Use the  LinkedList  class. Example: N=2 Sequence: 2, 3, 5, 4, 4, 7, 5, 6, 11, 7, 5, 9, 6, ...
Exercises (3) Write a program that reads a sequence of integers ending with 0 and sorts them in an increasing order. Use the  ArrayList  class. Write a program that finds in a given array of integers how many times each of them presents. Use  Hash Map  and  ArrayList . Example: array = {3, 4, 4, 2, 3, 3, 4, 3, 2} 2    2 times 3    4 times 4    3 times
Exercises (4) Write a program that removes from a given sequence all negative numbers. Write a program that removes from a given sequence all the numbers that present in it odd number of times. Example: {4, 2, 2, 5, 2, 3, 2, 3, 1, 5, 2}    {5, 3, 3, 5} By definition the majorant of an array is a value that occur in the least half of the elements of the array. Write a program to find the majorant of given array (if any). Example: {2, 2, 3, 3, 2, 3, 4, 3, 3}    3
Exercises (7) Write a program that counts how many times each word from a given text presents in it. The casing differences should be ignored. The result words should be ordered by their number of occurrences in the text. Example: is    2 the    2 this    3 text    6 This is the TEXT. Text, text, text – THIS TEXT! Is this the text?
Exercises (5) We are given numbers N and M and the following operations: N = N+1 N = N+2 N = N*2 Write a program that finds the shortest sequence of operations from the list above that starts from N and finishes in M Example: N = 5, M = 16 Sequence: 5    7    8    16
Exercises (6) We are given a labyrinth of size N x N. Some of its cells are empty (0) and some are full (x). We can move from an empty cell to another empty cell if they share common wall. Given a starting position (*) calculate and fill in the array the minimal distance from this position to any other cell in the array. Use &quot;u&quot; for the unreachable cells. Example: 0 0 0 x 0 x 0 x 0 x 0 x 0 * x 0 x 0 0 x 0 0 0 0 0 0 0 x x 0 0 0 0 x 0 x 3 4 5 x u x 2 x 6 x u x 1 * x 8 x 10 2 x 6 7 8 9 3 4 5 x x 10 4 5 6 x u x
Ad

More Related Content

What's hot (20)

Data structures (introduction)
 Data structures (introduction) Data structures (introduction)
Data structures (introduction)
Arvind Devaraj
 
Data structures
Data structuresData structures
Data structures
Saurabh Mishra
 
Datastructure
DatastructureDatastructure
Datastructure
Griffinder VinHai
 
Data structures
Data structuresData structures
Data structures
Sneha Chopra
 
Data structures Basics
Data structures BasicsData structures Basics
Data structures Basics
DurgaDeviCbit
 
Data Structure Using C
Data Structure Using CData Structure Using C
Data Structure Using C
CHANDERPRABHU JAIN COLLEGE OF HIGHER STUDIES & SCHOOL OF LAW
 
LectureNotes-03-DSA
LectureNotes-03-DSALectureNotes-03-DSA
LectureNotes-03-DSA
Haitham El-Ghareeb
 
Data structure lecture 1
Data structure lecture 1Data structure lecture 1
Data structure lecture 1
Kumar
 
Bca ii dfs u-1 introduction to data structure
Bca ii dfs u-1 introduction to data structureBca ii dfs u-1 introduction to data structure
Bca ii dfs u-1 introduction to data structure
Rai University
 
linked list (c#)
 linked list (c#) linked list (c#)
linked list (c#)
swajahatr
 
Data structures
Data structuresData structures
Data structures
Naresh Babu Merugu
 
Data structures using c
Data structures using cData structures using c
Data structures using c
Prof. Dr. K. Adisesha
 
LectureNotes-06-DSA
LectureNotes-06-DSALectureNotes-06-DSA
LectureNotes-06-DSA
Haitham El-Ghareeb
 
ADT STACK and Queues
ADT STACK and QueuesADT STACK and Queues
ADT STACK and Queues
BHARATH KUMAR
 
Unit 1 introduction to data structure
Unit 1   introduction to data structureUnit 1   introduction to data structure
Unit 1 introduction to data structure
kalyanineve
 
1 list datastructures
1 list datastructures1 list datastructures
1 list datastructures
Nguync91368
 
2 a stacks
2 a stacks2 a stacks
2 a stacks
Nguync91368
 
Data Structures (CS8391)
Data Structures (CS8391)Data Structures (CS8391)
Data Structures (CS8391)
Elavarasi K
 
Presentation on Elementary data structures
Presentation on Elementary data structuresPresentation on Elementary data structures
Presentation on Elementary data structures
Kuber Chandra
 
Data structure and algorithm All in One
Data structure and algorithm All in OneData structure and algorithm All in One
Data structure and algorithm All in One
jehan1987
 

Viewers also liked (20)

7. Tree - Data Structures using C++ by Varsha Patil
7. Tree - Data Structures using C++ by Varsha Patil7. Tree - Data Structures using C++ by Varsha Patil
7. Tree - Data Structures using C++ by Varsha Patil
widespreadpromotion
 
Data structure and its types
Data structure and its typesData structure and its types
Data structure and its types
Navtar Sidhu Brar
 
Introduction to data structures and Algorithm
Introduction to data structures and AlgorithmIntroduction to data structures and Algorithm
Introduction to data structures and Algorithm
Dhaval Kaneria
 
Lecture 1 data structures and algorithms
Lecture 1 data structures and algorithmsLecture 1 data structures and algorithms
Lecture 1 data structures and algorithms
Aakash deep Singhal
 
L6 structure
L6 structureL6 structure
L6 structure
mondalakash2012
 
01 05 - introduction xml
01  05 - introduction xml01  05 - introduction xml
01 05 - introduction xml
Siva Kumar reddy Vasipally
 
linked list
linked listlinked list
linked list
Abbott
 
Introduction to data structure by anil dutt
Introduction to data structure by anil duttIntroduction to data structure by anil dutt
Introduction to data structure by anil dutt
Anil Dutt
 
‫Chapter3 inheritance
‫Chapter3 inheritance‫Chapter3 inheritance
‫Chapter3 inheritance
Mahmoud Alfarra
 
Method overloading
Method overloadingMethod overloading
Method overloading
Lovely Professional University
 
5 Array List, data structure course
5 Array List, data structure course5 Array List, data structure course
5 Array List, data structure course
Mahmoud Alfarra
 
3 Array operations
3   Array operations3   Array operations
3 Array operations
Mahmoud Alfarra
 
Data Structure (Introduction to Data Structure)
Data Structure (Introduction to Data Structure)Data Structure (Introduction to Data Structure)
Data Structure (Introduction to Data Structure)
Adam Mukharil Bachtiar
 
Data structures
Data structuresData structures
Data structures
Lovely Professional University
 
Mca ii dfs u-1 introduction to data structure
Mca ii dfs u-1 introduction to data structureMca ii dfs u-1 introduction to data structure
Mca ii dfs u-1 introduction to data structure
Rai University
 
Trees data structure
Trees data structureTrees data structure
Trees data structure
Mahmoud Alfarra
 
Graphs data Structure
Graphs data StructureGraphs data Structure
Graphs data Structure
Mahmoud Alfarra
 
Tree Traversals (In-order, Pre-order and Post-order)
Tree Traversals (In-order, Pre-order and Post-order)Tree Traversals (In-order, Pre-order and Post-order)
Tree Traversals (In-order, Pre-order and Post-order)
raj upadhyay
 
data structure and algorithms
data structure and algorithmsdata structure and algorithms
data structure and algorithms
ibrar ahmad
 
‫‫Chapter4 Polymorphism
‫‫Chapter4 Polymorphism‫‫Chapter4 Polymorphism
‫‫Chapter4 Polymorphism
Mahmoud Alfarra
 
7. Tree - Data Structures using C++ by Varsha Patil
7. Tree - Data Structures using C++ by Varsha Patil7. Tree - Data Structures using C++ by Varsha Patil
7. Tree - Data Structures using C++ by Varsha Patil
widespreadpromotion
 
Data structure and its types
Data structure and its typesData structure and its types
Data structure and its types
Navtar Sidhu Brar
 
Introduction to data structures and Algorithm
Introduction to data structures and AlgorithmIntroduction to data structures and Algorithm
Introduction to data structures and Algorithm
Dhaval Kaneria
 
Lecture 1 data structures and algorithms
Lecture 1 data structures and algorithmsLecture 1 data structures and algorithms
Lecture 1 data structures and algorithms
Aakash deep Singhal
 
linked list
linked listlinked list
linked list
Abbott
 
Introduction to data structure by anil dutt
Introduction to data structure by anil duttIntroduction to data structure by anil dutt
Introduction to data structure by anil dutt
Anil Dutt
 
5 Array List, data structure course
5 Array List, data structure course5 Array List, data structure course
5 Array List, data structure course
Mahmoud Alfarra
 
Data Structure (Introduction to Data Structure)
Data Structure (Introduction to Data Structure)Data Structure (Introduction to Data Structure)
Data Structure (Introduction to Data Structure)
Adam Mukharil Bachtiar
 
Mca ii dfs u-1 introduction to data structure
Mca ii dfs u-1 introduction to data structureMca ii dfs u-1 introduction to data structure
Mca ii dfs u-1 introduction to data structure
Rai University
 
Tree Traversals (In-order, Pre-order and Post-order)
Tree Traversals (In-order, Pre-order and Post-order)Tree Traversals (In-order, Pre-order and Post-order)
Tree Traversals (In-order, Pre-order and Post-order)
raj upadhyay
 
data structure and algorithms
data structure and algorithmsdata structure and algorithms
data structure and algorithms
ibrar ahmad
 
‫‫Chapter4 Polymorphism
‫‫Chapter4 Polymorphism‫‫Chapter4 Polymorphism
‫‫Chapter4 Polymorphism
Mahmoud Alfarra
 
Ad

Similar to Basic data-structures-v.1.1 (20)

16 Linear data structures
16 Linear data structures16 Linear data structures
16 Linear data structures
maznabili
 
An Introduction to Stack Data Structures
An Introduction to Stack Data StructuresAn Introduction to Stack Data Structures
An Introduction to Stack Data Structures
berggold2024
 
introduction stacks in data structures and algorithms
introduction stacks in data structures and algorithmsintroduction stacks in data structures and algorithms
introduction stacks in data structures and algorithms
sneham64878
 
01-intro_stacks.ppt
01-intro_stacks.ppt01-intro_stacks.ppt
01-intro_stacks.ppt
soniya555961
 
Collection and framework
Collection and frameworkCollection and framework
Collection and framework
SARAVANAN GOPALAKRISHNAN
 
Collections generic
Collections genericCollections generic
Collections generic
sandhish
 
16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks Queues16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks Queues
Intro C# Book
 
Collections in object oriented programming
Collections in object oriented programmingCollections in object oriented programming
Collections in object oriented programming
KaranAgrawal78
 
Java Collections Framework
Java Collections FrameworkJava Collections Framework
Java Collections Framework
Sony India Software Center
 
Lec2
Lec2Lec2
Lec2
Anjneya Varshney
 
Array properties
Array propertiesArray properties
Array properties
Shravan Sharma
 
Aj unit2 notesjavadatastructures
Aj unit2 notesjavadatastructuresAj unit2 notesjavadatastructures
Aj unit2 notesjavadatastructures
Arthik Daniel
 
Data -structures for class 12 , easy ppt
Data -structures for class 12 , easy pptData -structures for class 12 , easy ppt
Data -structures for class 12 , easy ppt
anikedheikhamsingh
 
Stack linked list
Stack linked listStack linked list
Stack linked list
bhargav0077
 
Stack and Queue
Stack and Queue Stack and Queue
Stack and Queue
Apurbo Datta
 
Collections and its types in C# (with examples)
Collections and its types in C# (with examples)Collections and its types in C# (with examples)
Collections and its types in C# (with examples)
Aijaz Ali Abro
 
Java R20 - UNIT-3.pdf Java R20 - UNIT-3.pdf
Java R20 - UNIT-3.pdf Java R20 - UNIT-3.pdfJava R20 - UNIT-3.pdf Java R20 - UNIT-3.pdf
Java R20 - UNIT-3.pdf Java R20 - UNIT-3.pdf
kamalabhushanamnokki
 
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdf
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdfLabprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdf
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdf
freddysarabia1
 
9781439035665 ppt ch09
9781439035665 ppt ch099781439035665 ppt ch09
9781439035665 ppt ch09
Terry Yoast
 
DATASTRUCTURES UNIT-1
DATASTRUCTURES UNIT-1DATASTRUCTURES UNIT-1
DATASTRUCTURES UNIT-1
Malikireddy Bramhananda Reddy
 
16 Linear data structures
16 Linear data structures16 Linear data structures
16 Linear data structures
maznabili
 
An Introduction to Stack Data Structures
An Introduction to Stack Data StructuresAn Introduction to Stack Data Structures
An Introduction to Stack Data Structures
berggold2024
 
introduction stacks in data structures and algorithms
introduction stacks in data structures and algorithmsintroduction stacks in data structures and algorithms
introduction stacks in data structures and algorithms
sneham64878
 
01-intro_stacks.ppt
01-intro_stacks.ppt01-intro_stacks.ppt
01-intro_stacks.ppt
soniya555961
 
Collections generic
Collections genericCollections generic
Collections generic
sandhish
 
16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks Queues16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks Queues
Intro C# Book
 
Collections in object oriented programming
Collections in object oriented programmingCollections in object oriented programming
Collections in object oriented programming
KaranAgrawal78
 
Aj unit2 notesjavadatastructures
Aj unit2 notesjavadatastructuresAj unit2 notesjavadatastructures
Aj unit2 notesjavadatastructures
Arthik Daniel
 
Data -structures for class 12 , easy ppt
Data -structures for class 12 , easy pptData -structures for class 12 , easy ppt
Data -structures for class 12 , easy ppt
anikedheikhamsingh
 
Stack linked list
Stack linked listStack linked list
Stack linked list
bhargav0077
 
Collections and its types in C# (with examples)
Collections and its types in C# (with examples)Collections and its types in C# (with examples)
Collections and its types in C# (with examples)
Aijaz Ali Abro
 
Java R20 - UNIT-3.pdf Java R20 - UNIT-3.pdf
Java R20 - UNIT-3.pdf Java R20 - UNIT-3.pdfJava R20 - UNIT-3.pdf Java R20 - UNIT-3.pdf
Java R20 - UNIT-3.pdf Java R20 - UNIT-3.pdf
kamalabhushanamnokki
 
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdf
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdfLabprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdf
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdf
freddysarabia1
 
9781439035665 ppt ch09
9781439035665 ppt ch099781439035665 ppt ch09
9781439035665 ppt ch09
Terry Yoast
 
Ad

More from BG Java EE Course (20)

Rich faces
Rich facesRich faces
Rich faces
BG Java EE Course
 
JSP Custom Tags
JSP Custom TagsJSP Custom Tags
JSP Custom Tags
BG Java EE Course
 
Java Server Faces (JSF) - advanced
Java Server Faces (JSF) - advancedJava Server Faces (JSF) - advanced
Java Server Faces (JSF) - advanced
BG Java EE Course
 
Java Server Faces (JSF) - Basics
Java Server Faces (JSF) - BasicsJava Server Faces (JSF) - Basics
Java Server Faces (JSF) - Basics
BG Java EE Course
 
JSTL
JSTLJSTL
JSTL
BG Java EE Course
 
Unified Expression Language
Unified Expression LanguageUnified Expression Language
Unified Expression Language
BG Java EE Course
 
Java Server Pages
Java Server PagesJava Server Pages
Java Server Pages
BG Java EE Course
 
Web Applications and Deployment
Web Applications and DeploymentWeb Applications and Deployment
Web Applications and Deployment
BG Java EE Course
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
BG Java EE Course
 
CSS
CSSCSS
CSS
BG Java EE Course
 
HTML: Tables and Forms
HTML: Tables and FormsHTML: Tables and Forms
HTML: Tables and Forms
BG Java EE Course
 
HTML Fundamentals
HTML FundamentalsHTML Fundamentals
HTML Fundamentals
BG Java EE Course
 
WWW and HTTP
WWW and HTTPWWW and HTTP
WWW and HTTP
BG Java EE Course
 
JavaScript and jQuery Fundamentals
JavaScript and jQuery FundamentalsJavaScript and jQuery Fundamentals
JavaScript and jQuery Fundamentals
BG Java EE Course
 
Creating Web Sites with HTML and CSS
Creating Web Sites with HTML and CSSCreating Web Sites with HTML and CSS
Creating Web Sites with HTML and CSS
BG Java EE Course
 
Processing XML with Java
Processing XML with JavaProcessing XML with Java
Processing XML with Java
BG Java EE Course
 
Introduction to XML
Introduction to XMLIntroduction to XML
Introduction to XML
BG Java EE Course
 
Data Access with JDBC
Data Access with JDBCData Access with JDBC
Data Access with JDBC
BG Java EE Course
 
Introduction to-sql
Introduction to-sqlIntroduction to-sql
Introduction to-sql
BG Java EE Course
 
Introduction to-RDBMS-systems
Introduction to-RDBMS-systemsIntroduction to-RDBMS-systems
Introduction to-RDBMS-systems
BG Java EE Course
 

Recently uploaded (20)

SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdfSAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
Precisely
 
Generative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in BusinessGenerative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in Business
Dr. Tathagat Varma
 
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Impelsys Inc.
 
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul
 
Rusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond SparkRusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond Spark
carlyakerly1
 
Role of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered ManufacturingRole of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered Manufacturing
Andrew Leo
 
Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)
Ortus Solutions, Corp
 
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded DevelopersLinux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Toradex
 
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
SOFTTECHHUB
 
Drupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy ConsumptionDrupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy Consumption
Exove
 
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In FranceManifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
chb3
 
Quantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur MorganQuantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur Morgan
Arthur Morgan
 
Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025
Splunk
 
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
organizerofv
 
Big Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur MorganBig Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur Morgan
Arthur Morgan
 
TrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business ConsultingTrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business Consulting
Trs Labs
 
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-UmgebungenHCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
panagenda
 
Electronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploitElectronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploit
niftliyevhuseyn
 
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
BookNet Canada
 
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager APIUiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPathCommunity
 
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdfSAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
Precisely
 
Generative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in BusinessGenerative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in Business
Dr. Tathagat Varma
 
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Impelsys Inc.
 
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul
 
Rusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond SparkRusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond Spark
carlyakerly1
 
Role of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered ManufacturingRole of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered Manufacturing
Andrew Leo
 
Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)
Ortus Solutions, Corp
 
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded DevelopersLinux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Toradex
 
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
SOFTTECHHUB
 
Drupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy ConsumptionDrupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy Consumption
Exove
 
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In FranceManifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
chb3
 
Quantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur MorganQuantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur Morgan
Arthur Morgan
 
Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025
Splunk
 
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
organizerofv
 
Big Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur MorganBig Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur Morgan
Arthur Morgan
 
TrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business ConsultingTrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business Consulting
Trs Labs
 
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-UmgebungenHCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
panagenda
 
Electronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploitElectronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploit
niftliyevhuseyn
 
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
BookNet Canada
 
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager APIUiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPathCommunity
 

Basic data-structures-v.1.1

  • 1. Lists, Stacks, Queues, Trees, Hash Tables Basic Data Structures
  • 2. Contents Abstract Data Types (ADT) Lists – ArrayList Class Stacks – Stack Class Queues – Queue Class Trees – Terminology and Types Dictionaries – HashMap Class
  • 3. Abstract Data Types An Abstract Data Type (ADT) is a data type together with the operations, whose properties are specified independently of any particular implementation ADT are set of definitions of operations (like the interfaces in Java) Can have several different implementations Different implementations can have different efficiency
  • 4. Basic Data Structures Linear structures Lists: Variable-size Stacks: LIFO (last in first out) structure Queues: FIFO (first in first out) structure Trees Dictionaries (maps) Contain pairs (key, value) Hash tables: Unordered lists which use a ‘hash function’ to insert and search
  • 5. What Is a List?
  • 6. The List ADT List is linear data structure (container) that contains a sequence of elements (objects) Has variable size Objects are arranged linearly Can be implemented in several ways Statically (using array) Dynamically (linked implementation) Using the ArrayList class
  • 8. Static List Implemented by an array Provide direct access by index Usually has limited capacity Resizing is slow operation Slow insert and deletion 0 1 2 3 4 5 6 7 8 11 7 18 14 L 5 2 33 47 3
  • 9. Linked List Dynamic (pointer-based) implementation Different forms Singly-linked and doubly-linked Sorted and Unsorted Singly-linked List - each “Object” has “ value ” and “ next ” fields 11 next 7 next 18 next 14 next head null
  • 10. Linked List (2) Doubly-linked List - each “Object” has “ value ”, “ next ” and “ prev ” fields 11 next prev head tail 7 next prev 18 next prev 14 next prev null null
  • 12. The java.util.ArrayList Class Implements the list data structure using an array whose size is dynamically increased as needed Allocates in advance buffer space for new elements (for better performance) Insertion methods: add(Object) – adds an object at the end add (index , Object) – inserts an object to the list at a specified position size() – returns the number of elements
  • 13. The ArrayList Class Deletion methods: remove(Object) – removes the first occurrence of a specific object remove( index) – removes the element at the specified position clear() – removes all elements Other supported methods: c ontains() , t oArray()
  • 14. The ArrayList Class(2) ArrayList can contain any data type Elements are added directly Typecasting is required when extracting elements unless we use Generics Converting to array List list = new ArrayList(); list. a dd(5); // Add integer value list. a dd(&quot;some string&quot;); // Add string value int firstElement = ((Integer)(list.get(0))).intValue(); String secondElement = (String)list.get(1); Integer[] arr = list.toArray(new Integer[list.size()]);
  • 15. What are Generics Generics are classes or interfaces that can be instantiated with a variety of types They have 1 or more formal type parameters When using a generic you specify an actual type List<String> list = new ArrayList<String>(); String s = new String(&quot; li1 &quot;); list.add(s); list.add(5); // This will cause compile time error Specifies that String is actual type of this List 5 is not a String
  • 16. Primes[n..m] – Example Find all prime numbers in a specified interval public static ArrayList<Integer> getPrimes(int start, int end) { List<Integer> primesList = new ArrayList<Integer>(); for (int num = start; num <= end; num++) { boolean prime = true; for (int div = 2; div <= Math.sqrt(num); div++) { if (num % div == 0) { prime = false; break; } } if (prime) { primesList.add(num); } } return primesList; }
  • 18. Union and Intersection of Lists – Example public static Integer[] union(Integer[] firstArr, Integer[] secondArr) { List<Integer> union = new ArrayList<Integer>(); for (Integer item : firstArr) { union.add(item); } for (Integer item : secondArr) { if (!union.contains(item)) { union.add(item); } } return union.toArray(new Integer[union.size()]); } //Example continues...
  • 19. Union and Intersection of Lists – Example(2) public static Integer[] intersect(Integer[] firstArr, Integer[] secondArr) { List<Integer> intersect = new ArrayList<Integer>(); for (Integer item : firstArr) { if (Arrays.binarySearch(secondArr, item) >= 0) { intersect.add(item); } } return intersect.toArray( new Integer[intersect.size()]); }
  • 21. What is a Stack?
  • 22. The Stack ADT LIFO (last in first out) structure Elements inserted (push) at “top” Elements removed (pop) from “top” Can be implemented in several ways Statically (using array) Dynamically (linked implementation) Using the Stack class
  • 23. Static Stack Array-based (static) implementation Usually has limited capacity Has top variable, pointing to the top IsEMPTY( S ) Check if S.top = -1 0 1 2 3 4 5 6 7 8 11 7 18 14 S top
  • 24. Linked Stack Dynamic (pointer-based) implementation Each “object” has “value” and “next” fields Dynamically create and delete objects 11 next 7 next 18 next 14 next top null
  • 25. Using the Stack class
  • 26. The Stack Class – Overview Implements the stack data structure using an array whose size is dynamically increased as needed Major methods: push(object) – inserts elements to the stack pop() – removes and returns the top element from the stack peek() – returns the top element of the stack without removing it
  • 27. The Stack Class – More Methods Other methods: size() – returns the number of elements clear() – removes all elements contains(object) – determines whether given element is in the stack toArray() – converts the stack to array
  • 28. Examples Using the Stack class
  • 29. Stack – Example Using push() , pop() and peek() methods public static void main(String[] args) { Stack<String> stack = new Stack<String>(); stack.push(&quot;1. Ivan&quot;); stack.push(&quot;2. Nikolay&quot;); stack.push(&quot;3. Maria&quot;); stack.push(&quot;4. George&quot;); System.out.println(&quot;Top = &quot; + stack.peek()); while (stack.size() > 0) { String personName = stack.pop(); System.out.println(personName); } }
  • 30. Live Demo Using the Stack class
  • 31. Matching Brackets – Example We are given an arithmetical expression with brackets that can be nested. We want to extract all parts of the expression that are closed in brackets. Example: 1 + (3 + 2 - (2+3) * 4 - ((3+1)*(4-2))) Result: (2+3) (3+1) (4-2) ((3+1)*(4-2)) (3 + 2 - (2+3) * 4 - ((3+1)*(4-2)))
  • 32. Matching Brackets – Solution with a Stack String expression = &quot;1 + (3 + 2 - (2+3) * 4 - ((3+1)*(4-2)))&quot;; Stack<Integer> stack = new Stack<Integer>(); for (int i = 0; i < expression.length(); i++) { char ch = expression.charAt(i); if (ch == '(') { stack.push(i); } else if (ch == ')') { int startIndex = (int) stack.pop(); String contents = expression.substring(startIndex, i + 1); System.out.println(contents); } }
  • 33. Live Demo Matching Brackets
  • 34. What is a Queue?
  • 35. The Queue ADT FIFO (first in first out) structure Elements inserted at tail (enqueue) Elements removed from head ( dequeue ) Useful in many situations Processing jobs, print queues, messages Can be implemented in several ways Statically (using array) Dynamically (using pointers) Using the LinkedList class
  • 36. Static Queue Static (array-based) implementation Queue has limited (fixed) capacity Implement as a “circular array” Maintain Q.Capacity and Q.Length Has head and tail variables, pointing to the head and the tail 0 1 2 3 4 5 6 7 8 11 7 18 14 Q head tail
  • 37. Linked Queue Dynamic (pointer-based) implementation Each “object” has “ value ” and “ next ” fields Dynamically create and delete objects 11 next 7 next 18 next 14 next head tail null
  • 38. Using the LinkedList class
  • 39. The LinkedList Class – Overview Implements the queue data structure using a doubly-linked list Major methods: offer(object) – adds an object to the end of the queue poll() – removes and returns the object at the beginning of the queue peek() – returns the object at the beginning of the queue without removing it
  • 40. The LinkedList Class – More Methods Other methods: size() – gets the number of elements contained in the queue clear() – removes all elements from the queue contains(object) – determines whether given element is in the queue toArray () – converts the queue to array
  • 41. Examples Using the LinkedList class
  • 42. Queue – Example Using offer () and poll () methods public static void main(String[] args) { Queue<String> queue = new LinkedList<String>(); queue.offer(&quot;Message One&quot;); queue.offer(&quot;Message Two&quot;); queue.offer(&quot;Message Three&quot;); queue.offer(&quot;Message Four&quot;); queue.offer(&quot;Message Five&quot;); while (queue.size() > 0) { String msg = queue.poll(); System.out.println(msg); } }
  • 43. Live Demo Using the LinkedList class
  • 44. Sequence N, N+1, 2*N We are given the sequence: 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 given number P Example: N = 3, P = 16 S = 3, 4, 6, 5, 8, 7, 12, 6, 10, 9, 16, 8, 14, ... Index of P = 11 +1 *2 +1 *2 +1 *2
  • 45. Sequence – Solution int n = 3; int p = 16; Queue<Integer> queue = new LinkedList<Integer>(); queue.offer(n); int index = 0; while (queue.size() > 0) { index++; int current = queue.poll(); if (current == p) { System.out.println(&quot;Index = &quot; + index); return; } queue.offer(current + 1); queue.offer(2 * current); }
  • 46. Live Demo Sequence N, N+1, 2*N
  • 47. Definition, Types of Trees What is Tree?
  • 48. Trees Terminology Node, edge, root, child, children, siblings, parent, ancestor, descendant, predecessor, successor, internal node, leaf, depth, height 17 15 14 9 6 5 8 Height = 2 Depth 0 Depth 1 Depth 2
  • 49. Binary Trees Binary trees: most used form Each node has at most 2 children 10 17 15 9 6 5 8 “ right child” “ left subtree” “ root” “ left child”
  • 50. Binary Trees Traversals Traversal can be done in pre-order, in-order and post-order Pre-order: left, root, right – 6, 9, 12, 17, 19, 25 In-order: root, left, right – 17, 9, 6, 12, 19, 25 Post-order: left, right, root – 6, 12, 9, 25, 19, 17 17 19 9 6 12 25
  • 51. Binary Search Trees Binary search trees are ordered A binary tree in which binary-search-tree property holds: For each node x in the tree All the elements of the left subtree of x are ≤ x All the elements of the right subtree of x are > x Binary search trees can be balanced Balanced trees has low height
  • 52. Binary Search Trees Example of binary search tree If the tree is balanced, adding, searching, and deletion operations take approx. log( n ) steps 17 19 9 6 12 25
  • 53. What is a Dictionary (Map)?
  • 54. The Dictionary (Map) ADT The ADT &quot;dictionary&quot; maps key to values Also known as &quot;map&quot; or &quot;associative array&quot; Contains a set of (key, value) pairs Dictionary ADT operations: ADD(key, value) FIND_BY_KEY(key)  value DELETE(key) Can be implemented in several ways List, array, hash table, balanced tree, ...
  • 55. What is a Hash Table?
  • 56. Hash Table A hash table is an array that holds a set of (key, value) pairs The process of mapping a key to a position in a table is called hashing 0 1 2 3 4 5 m-1 ... ... ... ... T h( k ) ... ... ...
  • 57. Hash Functions and Hashing A hash function maps keys to positions It is denoted by h The hash table has m slots, indexed from 0 to m-1 For any value k in the key range and some hash function h h( k ) = i 0  i < m 0 1 2 3 4 5 m-1 ... ... ... ... T h( k ) ... ... ...
  • 58. Mapping Functions Perfect hashing function (PHF) h(k) : one-to-one mapping from each key k to integers in [ 0 , m -1 ] The PHF maps each key to a distinct integer within some manageable range Finding a perfect hashing function is in most cases impossible More realistically Hash functions h(k) map most of the keys onto unique integers, but not all
  • 59. Collisions in Hash Tables Collision is the situation when different keys can have the same hash value h(k 1 ) = h(k 2 ) for k 1 ≠ k 2 When the number of collisions is sufficiently small, the hash tables work quite well (fast) Several collisions resolution strategies Chaining in a list, re-hashing, using the neighboring slots (linear probing), ...
  • 60. Collision Resolution - Chaining h( &quot;Pesho&quot; ) = 4 h( &quot;Lili&quot; ) = n-1 h( &quot;Kiro&quot; ) = 2 h(&quot;Mimi&quot;) = 1 h(&quot;Ivan&quot;) = 2 null T 0 1 2 3 4 5 n-1 null ... null chaining Kiro Ivan collision null Mimi null Lili null Pesho null
  • 61. Using the Hash Map class
  • 62. The Hash Map Class – Overview Implements the ADT dictionary as array dynamically increased as needed Contains a collection of key-and-value pairs arranged by the hash code of the key Collisions are resolved by chaining The Hash Map class relies on Object. h ashCode() method for calculating the hash codes of the elements Object. equals( ) method for comparing elements
  • 63. The Hash Map Class – Major Operations Major operations: put (key , value) – adds an element with the specified key and value into the hash table remove(key ) – removes the element with the specified key from the hash table get(key ) – returns element by key clear() – removes all elements from the hash table
  • 64. The Hash Map Class – More Operations More operations: size() – returns the number of elements c ontains Key (key ) – determines whether the hash table contains given key c ontainsValue(value) – determines whether the hash table contains given value keySet( ) – returns a set of the keys values() – returns a collection of the values
  • 65. Examples Using the HashMap Class
  • 66. Hashtable - Example Map<String, Integer> studentsMarks = new HashMap<String, Integer>(); studentsMarks.put(&quot;Ivan&quot;, 4); studentsMarks.put(&quot;Peter&quot;, 6); studentsMarks.put(&quot;Maria&quot;, 6); studentsMarks.put(&quot;George&quot;, 5); int peterMark = studentsMarks.get(&quot;Peter&quot;); studentsMarks.remove(&quot;Peter&quot;); System.out.println(&quot;Is Peter in the hash table: &quot; + studentsMarks.containsKey(&quot;Peter&quot;)); for (Map.Entry<String, Integer> studentMark : studentsMarks.entrySet()) { System.out.printf(&quot;%s --> %d%n&quot;, studentMark.getKey(), studentMark.getValue()); }
  • 67. Live Demo Using the HashMap Class
  • 68. Counting Words in a Text String s = &quot;Welcome to our Java course. In this &quot; + &quot;course you will learn how to write simple &quot; + &quot;programs in Java&quot;; String[] words = s.split(&quot;[ ,.]&quot;); Map<String, Integer> wordsCount = new HashMap<String, Integer>(); for (String word : words) if (!&quot;&quot;.equalsIgnoreCase(word)) { int count = 1; if (wordsCount.containsKey(word)) count += wordsCount.get(word); wordsCount.put(word, count); } for (String word : wordsCount.keySet()) System.out.printf(&quot;%s --> %d%n&quot;, word, wordsCount.get(word));
  • 69. Live Demo Counting Words in a Text
  • 70. Summary ADT are defined by list of operations independent of the implementation The basic data structures in the computer programming are List – ArrayList class in Java Stack – Stack class in Java Queue – LinkedList class in Java Trees – can be binary, balanced, search trees, etc. Dictionaries – Hash Map class in Java
  • 71. Basic Data Structures Questions?
  • 72. Exercises Write a program that reads from the console a sequence of positive integer numbers. The sequence ends when the number 0 is entered. Calculate and print the sum and average of the elements of the sequence. Use the ArrayList class. Write a method that finds the longest subsequence of equal numbers in given array. Use the ArrayList class. Write a program that reads N integers from the console and reverses them using a stack. Use the Stack class.
  • 73. Exercises (2) We are given the following sequence: S 1 = N; S 2 = S 1 + 1; S 3 = 2*S 1 + 1; S 4 = S 1 + 2; S 5 = S 2 + 1; S 6 = 2*S 2 + 1; S 7 = S 2 + 2; ... Write a program to print its first 100 elements for given N. Use the LinkedList class. Example: N=2 Sequence: 2, 3, 5, 4, 4, 7, 5, 6, 11, 7, 5, 9, 6, ...
  • 74. Exercises (3) Write a program that reads a sequence of integers ending with 0 and sorts them in an increasing order. Use the ArrayList class. Write a program that finds in a given array of integers how many times each of them presents. Use Hash Map and ArrayList . Example: array = {3, 4, 4, 2, 3, 3, 4, 3, 2} 2  2 times 3  4 times 4  3 times
  • 75. Exercises (4) Write a program that removes from a given sequence all negative numbers. Write a program that removes from a given sequence all the numbers that present in it odd number of times. Example: {4, 2, 2, 5, 2, 3, 2, 3, 1, 5, 2}  {5, 3, 3, 5} By definition the majorant of an array is a value that occur in the least half of the elements of the array. Write a program to find the majorant of given array (if any). Example: {2, 2, 3, 3, 2, 3, 4, 3, 3}  3
  • 76. Exercises (7) Write a program that counts how many times each word from a given text presents in it. The casing differences should be ignored. The result words should be ordered by their number of occurrences in the text. Example: is  2 the  2 this  3 text  6 This is the TEXT. Text, text, text – THIS TEXT! Is this the text?
  • 77. Exercises (5) We are given numbers N and M and the following operations: N = N+1 N = N+2 N = N*2 Write a program that finds the shortest sequence of operations from the list above that starts from N and finishes in M Example: N = 5, M = 16 Sequence: 5  7  8  16
  • 78. Exercises (6) We are given a labyrinth of size N x N. Some of its cells are empty (0) and some are full (x). We can move from an empty cell to another empty cell if they share common wall. Given a starting position (*) calculate and fill in the array the minimal distance from this position to any other cell in the array. Use &quot;u&quot; for the unreachable cells. Example: 0 0 0 x 0 x 0 x 0 x 0 x 0 * x 0 x 0 0 x 0 0 0 0 0 0 0 x x 0 0 0 0 x 0 x 3 4 5 x u x 2 x 6 x u x 1 * x 8 x 10 2 x 6 7 8 9 3 4 5 x x 10 4 5 6 x u x

Editor's Notes

  • #2: * 12/04/10 07/16/96 (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #3: * 12/04/10 07/16/96 (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #6: * 12/04/10 07/16/96 (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #8: * 12/04/10 07/16/96 (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #11: * 12/04/10 07/16/96 (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #12: * 12/04/10 07/16/96 (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #18: * 12/04/10 07/16/96 (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #21: * 12/04/10 07/16/96 (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #22: * 12/04/10 07/16/96 (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #26: * 12/04/10 07/16/96 (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #29: * 12/04/10 07/16/96 (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #31: * 12/04/10 07/16/96 (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #34: * 12/04/10 07/16/96 (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #35: * 12/04/10 07/16/96 (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #39: * 12/04/10 07/16/96 (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #42: * 12/04/10 07/16/96 (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #44: * 12/04/10 07/16/96 (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #47: * 12/04/10 07/16/96 (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #48: * 12/04/10 07/16/96 (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #51: * 12/04/10 07/16/96 (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #52: * 12/04/10 07/16/96 (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #53: * 12/04/10 07/16/96 (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #54: * 12/04/10 07/16/96 (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #56: * 12/04/10 07/16/96 (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #57: * 12/04/10 07/16/96 (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #62: * 12/04/10 07/16/96 (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #66: * 12/04/10 07/16/96 (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #68: * 12/04/10 07/16/96 (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #70: * 12/04/10 07/16/96 (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #71: * 12/04/10 07/16/96 (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #73: * 12/04/10 07/16/96 (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #77: * 12/04/10 07/16/96 (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #78: * 12/04/10 07/16/96 (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #79: * 12/04/10 07/16/96 (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##