Presentation is loading. Please wait.

Presentation is loading. Please wait.

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.

Similar presentations


Presentation on theme: "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."— Presentation transcript:

1 11 Tirgul 10 Data Structures

2 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!

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

4 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

5 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());

6 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 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

8 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?

9 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 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 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 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 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 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 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 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 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 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 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 1 5 3 7 2 null 2

20 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 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 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 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 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 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 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 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 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 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)

30 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.

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

32 Tree Terminology 32

33 Tree Terminology 33

34 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 ) = {

35 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. 17 1119

36 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.

37 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

38 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

39 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

40 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++; }

41 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); }

42 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()); }

43 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 44 Example 2 1 3 4 8 6 5 7 2.4 2.5 Given the following array: 2 3 8 4 5 7 6 1 2.5 2.4 The resulting tree is:

45 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? 2 1 3 4 8 6 5 7 2.4 2.5

46 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?

47 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).

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

49 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 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.)

51 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”]

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

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

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

55

56

57 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; }


Download ppt "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."

Similar presentations


Ads by Google