11 Tirgul 10 Data Structures. 2 Linked Lists Separate the logical order of items from their physical order in memory Each item points to the location.

Slides:



Advertisements
Similar presentations
Chapter 7. Binary Search Trees
Advertisements

David Weinberg presents Linked Lists: The Background  Linked Lists are similar to ArrayLists in their appearance and method of manipulation  They do.
1 abstract containers hierarchical (1 to many) graph (many to many) first ith last sequence/linear (1 to 1) set.
Binary Trees. DCS – SWC 2 Binary Trees Sets and Maps in Java are also available in tree-based implementations A Tree is – in this context – a data structure.
©Brooks/Cole, 2003 Chapter 12 Abstract Data Type.
1 Trees Tree nomenclature Implementation strategies Traversals –Depth-first –Breadth-first Implementing binary trees Reading: L&C 9.1 – 9.7.
DictionaryADT and Trees. Overview What is the DictionaryADT? What are trees? Implementing DictionaryADT with binary trees Balanced trees DictionaryADT.
1 Chapter 24 Lists Stacks and Queues. 2 Objectives F To design list with interface and abstract class (§24.2). F To design and implement a dynamic list.
Stacks with Dynamic Memory Class Signature Class Node {public Data data; public Node next; } Class Stack {private Node top; public Stack(); public void.
Fall 2007CS 2251 Iterators and Tree Traversals. Fall 2007CS 2252 Binary Trees In a binary tree, each node has at most two subtrees A set of nodes T is.
CS 104 Introduction to Computer Science and Graphics Problems Data Structure & Algorithms (4) Data Structures 11/18/2008 Yang Song.
BST Data Structure A BST node contains: A BST contains
©Brooks/Cole, 2003 Chapter 12 Abstract Data Type.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L12 (Chapter 20) Lists, Stacks,
Chapter 12 C Data Structures Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
COMP 110 Introduction to Programming Mr. Joshua Stough.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 12 – Data Structures Outline 12.1Introduction.
1 abstract containers hierarchical (1 to many) graph (many to many) first ith last sequence/linear (1 to 1) set.
Marc Smith and Jim Ten Eyck
Binary Trees Michael R. Wick
Comp 249 Programming Methodology Chapter 15 Linked Data Structure - Part B Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.
Chapter 12 Data Structure Associate Prof. Yuh-Shyan Chen Dept. of Computer Science and Information Engineering National Chung-Cheng University.
Chapter Tow Search Trees BY HUSSEIN SALIM QASIM WESAM HRBI FADHEEL CS 6310 ADVANCE DATA STRUCTURE AND ALGORITHM DR. ELISE DE DONCKER 1.
Lists ADT (brief intro):  Abstract Data Type  A DESCRIPTION of a data type  The data type can be anything: lists, sets, trees, stacks, etc.  What.
CM0551 Exam Prep. What are an algorithm’s time and space complexity? (2 marks) Answer: The growth rate of the algorithm’s time requirement and the computer.
Lecture Objectives  To learn how to use a tree to represent a hierarchical organization of information  To learn how to use recursion to process trees.
Information and Computer Sciences University of Hawaii, Manoa
© 2011 Pearson Addison-Wesley. All rights reserved 11 B-1 Chapter 11 (continued) Trees.
Topic 14 The BinaryTree ADT Objectives Define trees as data structures Define the terms associated with trees Discuss tree traversal algorithms.
1 Trees A tree is a data structure used to represent different kinds of data and help solve a number of algorithmic problems Game trees (i.e., chess ),
Stacks with Dynamic Memory Class Signature Class Node {public Data data; public Node next; } Class Stack {private Node top; public Stack(); public void.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 20 Lists, Stacks,
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 16 Binary.
Chapter 19: Binary Trees Java Programming: Program Design Including Data Structures Program Design Including Data Structures.
1 Chapter 17 Object-Oriented Data Structures. 2 Objectives F To describe what a data structure is (§17.1). F To explain the limitations of arrays (§17.1).
Starting at Binary Trees
Topic 15 The Binary Search Tree ADT Binary Search Tree A binary search tree (BST) is a binary tree with an ordering property of its elements, such.
COP INTERMEDIATE JAVA Data Structures. A data structure is a way of organizing a collection of data so that it can be manipulated effectively. A.
Slide 1 Linked Data Structures. Slide 2 Learning Objectives  Nodes and Linked Lists  Creating, searching  Linked List Applications  Stacks, queues.
Copyright © 2002 Pearson Education, Inc. Slide 1.
IKI 10100I: Data Structures & Algorithms Ruli Manurung (acknowledgments to Denny & Ade Azurat) 1 Fasilkom UI Ruli Manurung (Fasilkom UI)IKI10100I: Data.
Week 10 - Friday.  What did we talk about last time?  Graph representations  Adjacency matrix  Adjacency lists  Depth first search.
1/14/20161 BST Operations Data Structures Ananda Gunawardena.
Binary Search Trees (BST)
Tirgul 10. What We Will See Today:  Linked lists  Graphs  Trees  Iterators and Generators.
1 Joe Meehean. A A B B D D I I C C E E X X A A B B D D I I C C E E X X  Terminology each circle is a node pointers are edges topmost node is the root.
Reading data into sorted list Want to suck text file in and produce sorted list of the contents: Option 1 : read directly into array based list, sort afterwards.
BINARY TREES Objectives Define trees as data structures Define the terms associated with trees Discuss tree traversal algorithms Discuss a binary.
CS6045: Advanced Algorithms Data Structures. Dynamic Sets Next few lectures will focus on data structures rather than straight algorithms In particular,
IKI 10100: Data Structures & Algorithms Ruli Manurung (acknowledgments to Denny & Ade Azurat) 1 Fasilkom UI Ruli Manurung (Fasilkom UI)IKI10100: Lecture13.
Data Structures Intro2CS – week Stack ADT (Abstract Data Type) A container with 3 basic actions: – push(item) – pop() – is_empty() Semantics: –
Linked Data Structures
The Tree ADT.
Data Structure By Amee Trivedi.
Chapter 12 – Data Structures
Trees Chapter 15.
Trees Chapter 11 (continued)
Tirgul 12 Data Structures (2) 1.
Trees Chapter 11 (continued)
Tirgul 12 Data Structures 1.
Chapter 17 Object-Oriented Data Structures
Map interface Empty() - return true if the map is empty; else return false Size() - return the number of elements in the map Find(key) - if there is an.
Prof. Neary Adapted from slides by Dr. Katherine Gibson
Lesson Objectives Aims
Stacks with Dynamic Memory
CS6045: Advanced Algorithms
Stacks with Dynamic Memory
BINARY TREE CSC248 – Data Structure.
Presentation transcript:

11 Tirgul 10 Data Structures

2 Linked Lists Separate the logical order of items from their physical order in memory Each item points to the location of the next item Each item in the list is called a node Dynamically allocate nodes as needed Linked lists may also be used to implement other data structures, like queues and stacks Always remember that when a link to an item is destroyed – the item can not be reached!

33 Linked List Nodes class Node { Object data; Node next; } next data next data next data null head

44 Iterators Provide an efficient way to traverse a data structure while protecting its encapsulation Data structure provides an object implementing an iterator interface: public interface ObjectListIterator { public boolean hasNext(); public Objecct next(); } Returns true iff there are more items to iterate over Gets the next item in the list

55 Using iterators The iterator class must have access to the data structure’s internal members, so it is usually defined as an inner class or part of the same package Using an iterator to print a list: ObjectListIterator it=list.iterator(); while (it.hasNext()) System.out.println(it.next());

66 Linked List implementation public class ObjectList { protected static class Node { Object data; Node next; Node(Object d, Node n){data=d; next=n;} } protected Node head; public ObjectList() {head=null;} Nested class The first Node in the list

7 Linked List implementation protected static Node clone(Node node) { if (node==null) return null; return new Node(node.data, clone(node.next)); } public ObjectList(ObjectList list) { head = clone(list.head); } Recursively returns a copy of the sub-list starting with the given node Copy constructor

88 Linked List implementation public void addFirst(Object d){ head = new Node(d,head); } public Object removeFirst(){ Object d = head.data; head = head.next; return d; } What does this method assume?

99 Linked List implementation public boolean isEmpty(){ return head==null; } public String toString(){ String s = “”; for(Node n=head; n!=null; n=n.next) s += n.data.toString() + “ “; return s; } Loop over all nodes in the list

10 Linked List implementation protected class MyIterator implements ObjectListIterator { Node current; MyIterator() {current=head;} public boolean hasNext() {…} public Object next() {…} } public ObjectListIterator iterator() { return new MyIterator(); } Inner class Return an iterator for this list

11 Stack A stack is a Last-In-First-Out (LIFO) data structure The stack interface is: push, pop, isEmpty Implementing a stack using a linked list is trivial

12 Queue A queue is a First-In-First-Out (FIFO) data structure The queue interface is: enqueue, dequeue, isEmpty Enqueue - Enter new element to queue. Dequeue – Remove the element which was first entered the queue.

13 Queue Implementation of Queue with linked lists can be done in two ways: Enqueue to tail, dequeue from head. Enqueue to head, dequeue from tail. In order to implement a queue using the second option, we need a removeLast method Iterate over the entire list, or Use a doubly-linked list with a tail data member pointing to the last node

14 removeLast (no tail) public Object removeLast() { if (head.next == null) // singleton return removeFirst(); Node before = head; Node after = head.next; while (after.next != null) { before = after; after = after.next; } before.next = null; return after.data; } What does this method assume?

15 A doubly-linked list with a tail public class ObjectList { protected static class Node { Object data; Node next, prev; Node(Object d, Node p, Node n) { data=d; prev=p; next=n; } protected Node head, tail; public ObjectList() { head = tail = null; }

16 A doubly-linked list with a tail public void addFirst(Object d) { Node node = new Node(d, null, head); if (head == null) // list was empty tail = node; else // connect old head to new node head.prev = node; // update head head = node; }

17 A doubly-linked list with a tail public Object removeFirst() { Object d = head.data; head = head.next; if (head == null) // list is now empty tail = null; else { // disconnect old head head.prev.next = null; head.prev = null; } return d; } 17 What does this method assume?

18 A doubly-linked list with a tail public Object removeLast(){ Object d = tail.data; tail = tail.prev; if (tail == null) // list is now empty head = null; else { // disconnect old tail tail.next.prev = null; tail.next = null; } return d; } What does this method assume?

19 CountIntList Each integer will appear at most once in the list Maintain a counter of how many times each number was added Keep the list sorted The input 5,2,7,5,5,7 results in the following CountIntList: count data null 2

20 CountIntList public class CountIntList { protected static class Node { int data; int count; Node next; Node(int d, Node n) { data=d; count=1; next=n; } } protected Node head; public CountIntList() {head=null;}

21 CountIntList Protected Node lowerBound(int d) { if(head == null || d < head.data) return null; Node before = head; Node after = head.next; while(after != null && after.data <= d){ before = after; after = after.next; } return before; } In order to add new data d, we need to find the Node containing the largest data ≤ d

22 CountIntList public void add(int d) { Node prev = lowerBound(d); if(prev==null) // add new Node at head head = new Node(d, head); else if (prev.data==d) prev.count++; //update existing Node else // add new Node after prev prev.next = new Node(d, prev.next); } Add the given data to the CountIntList

23 Student grade DB public class Student { private String name; private int[] grades; public Student(String name, int[] grades) {…} public Student(Student s) {…} public int getGrade(int subject) { return grades[subject]; } public String getName() {return name;} } We want a DB of students sorted by their grades in each subject

24 A multi-linked list grades name {99,75,99} Alice next[] {80,80,75} Bob {75,99,80} Charlie null head[1]head[2]head[0]

25 Grades DB public class GradesDB { public static final int SUBJECT_NUM = 3; protected static class Node { Student data; Node[] next = new Node[SUBJECT_NUM]; Node(Student s) {data = new Student(s);} int grade(int i) {return data.getGrade(i);} } protected Node[] head = new Node[SUBJECT_NUM];

26 Grades DB public void add(Student stud) { Node node = new Node(stud); for (int i=0; i<SUBJECT_NUM; i++) add(i, node); } protected void add(int i, Node node) { Node prev = lowerBound(i, node.data); if (prev==null) { // add node at head node.next[i] = head[i]; head[i] = node; } else { // add node after prev node.next[i] = prev.next[i]; prev.next[i] = node; } Add a student to the DB Add a node to list #i

27 Grades DB protected Node lowerBound(int i, Student stud) { int grade = stud.getGrade(i); if (head[i]==null || grade < head[i].grade(i)) return null; Node before = head[i]; Node after = head[i].next[i]; while (after!=null && after.grade(i)<=grade) { before = after; after = after.next[i]; } return before; } Return the node which should come before the given student in list #i

28 Grades DB public String getRanking(int subject) { String ranking = “”; for (Node n = head[subject]; n!=null; n = n.next[subject]) ranking += n.data.getName() + ‘ ‘; return ranking; } Return the student names sorted by their grade in the given subject For example, getRanking(2) returns “Bob Charlie Alice”

29 Linked Lists vs. Arrays OperationLinked ListArray Insert at headO(1)O(n) Insert at middleO(n), O(1) given a referenceO(n) Remove from headO(1)O(n) Remove from middleO(n), O(1) given a referenceO(n) Find k-th elementO(k)O(1) Search unsortedO(n) Search sortedO(n)O(log n)

Tree Structures 30 A tree is a hierarchical structure that places elements in nodes along branches that originate from a root. Nodes in a tree are subdivided into levels in which the topmost level holds the root node.

Binary Tree 31 In a binary tree each node has at most two successors.

Tree Terminology 32

Tree Terminology 33

Height of a Binary Tree 34 The height of a binary tree is the length of the longest path from the root to a leaf node. Let T N be the subtree with root N and T L and T R be the roots of the left and right subtrees of N. Then -1if T N is empty 1+max( height(T L ), height(T R ))if T N not empty height(N) = height(T N ) = {

Binary Search Tree 35 A binary search tree is a binary tree where every node's left subtree holds values less than the node's value, and every right subtree holds values greater

Recursive Binary Tree-Scan Algorithms 36 To scan a tree recursively we must visit the node (N), scan the left subree (L), and scan the right subtree (R). The order in which we perform the N, L, R tasks determines the scan algorithm.

Inorder Scan 37 The inorder scan of a tree visits the left subtree L, visits the node N, then visits the right subtree R. To scan the entire tree, begin with the root. Scan order: B D A E C

Recursive Scanning Example 38 Preorder (NLR):A B D G C E H I F Inorder (LNR):D G B A H E I C F Postorder (LRN):G D B H I E F C A

Binary trees in Java 39 public class Node { protected Comparable data; protected Node left,right; public Node(Comparable data) { data = data; left = right = null; } public void addRight(Node node) { right = node; } public void addLeft(Node node) { left = node; } public Node getRight() { return right; } public Node getLeft() { return left; } public Comparable getData() { return data; } } //class

Binary Search Tree 40 public class BinTree { protected Node root; protected int size; public BinTree() { size = 0; } public void add(Comparable data) { add(data,root,root); size++; }

Recursive method to add 41 private void add(Comparable data, Node son, Node father) { //stop the recursion, we have reached a leaf if (son == null) { if (father == null) { //this leaf is the root root = new Node(data); } else { //just a regular leaf if ((father.getData()).compare(data) > 0) father.addLeft(new Node(data)); else father.addRight(new Node(data)); } } else { if ((son.getData()).compare(data) > 1) add(data, son.getLeft(), son); else add(data, son.getRight(), son); }

Recursive method to travel 42 /** * Recursive method: * Traversal of the tree (inorder). */ private void traverse(Node node) { if (node != null) { traverse(node.getLeft()); System.out.println(node.getData()); traverse(node.getRight()); }

Sorting an array using a binary search tree 43 Inorder traversal of a binary search tree always gives a sorted sequence of the values. Given a set of unordered elements, the following method can be used to Sort the elements: 1.construct a binary search tree whose keys are those elements, and then 2.perform an inorder traversal of this tree.

44 Example Given the following array: The resulting tree is:

Sorting an array using a binary search tree 45 Inorder traversal of this tree will result in: 1,2,2.4,2.5,3,4,5,6,7,8 What is the complexity of binary search tree sorting?

Sorting an array using a binary search tree 46 Insertion of element into binary search tree in the average case is: O(log(n)). Inorder traversal - O(n)). Total complexity - O((n)log(n)). What is the complexity in the worst case?

Expression trees 47 In the current exercise you are required to represent a mathematical expression as a tree. The tree nodes are instances of the classes: Number, Variable or Operator, (all of them implement the provided Expression interface).

Expression trees 48 An expression tree for the expression: (3+4)*5 An expression tree for the expression: 3+4*5

Building an expression tree from an expression 49 You are provided with a tokenizer that tells you the type of the next element in the expression. One of your goals is to write the class Parser, that builds a tree from String, using Tokenizer.

50 Expression To build a tree composed of Number, Variable and Operator, recursively break expression into blocks of: Term, Factor and Expression. Expression can be: Term { [+/-] Term} Term can be: Factor { [*/÷] Factor} Factor can be: Number Variable (Expression) [meaning: Expression inside brackets] (Elements in {} can appear 0 or more times.)

parseExpression [“8+5*(2-x)”] parseTerm [“8”] parseTerm [“5*(2-x)”] + parseFactor [“(2-x)”] * parseFactor[“8”] Number[“8”] parseExpression [“2-x”] () parseTerm [“x”] - Example: parseExpression[“8+5*(2-x)”] parseFactor[“5”] Number[“5”] parseFactor[“x”] Variable[“x”] parseTerm[“2”] parseFactor[“2”] Number[“2”]

x - 2 * And the resulted tree for: 8+5*(2-x) is:

Exam question: 2009a מחסנית ותור פלינדרום מחסנית פלינדרום הינה מחסנית אשר הינה סימטרית מבחינת הערכים בה. לדוגמא, המחסניות הבאות הינן מחסניות פלינדרום ( החיצים מסמנים את ראש המחסנית ):

תור פלינדרום הינה הינו תור אשר סימטרי מבחינת הערכים בו. למשל :

public static boolean checkPalindrom2(Stack s1, int numOfElements){ int i; int tempVal=0; Queue q2=new Queue(); // move all items to q2 and for (i=1;i<=numOfElements;i++){ tempVal=q1.dequeue (); q2.enqueue(tempVal); } // return half of the item to the original stack for (i=1;i<=numOfItems/2;i++){ tempVal=q2.dequeue(); s1.push(tempVal); } //if the number of items is odd: ignore middle item. if ((numOfItems % 2) != 0) tempVal=q2.dequeue(); // now the q2 holds half of the items in a reversed //order, and s1 holds half of the item in their original //order. Compare the items for (i=1;i<=numOfItems/2;i++){ { if (s1.pop()!=q2.dequeue()) return false; } return true; }