Presentation is loading. Please wait.

Presentation is loading. Please wait.

Tirgul 12 Data Structures (2) 1.

Similar presentations


Presentation on theme: "Tirgul 12 Data Structures (2) 1."— Presentation transcript:

1 Tirgul 12 Data Structures (2) 1

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 Linked List Nodes class Node<E> { E data; Node next; } head next
null next next next data data data

4 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 ListIterator<E> extends Iterator<E> { public boolean hasNext(); public E next(); } Returns true iff there are more items to iterate over Gets the next item in the list

5 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: ListIterator<MyObject> it=list.iterator(); while (it.hasNext()) System.out.println(it.next());

6 Linked List implementation
public class List<E> implements Iterable<E> { private class Node { private E data; private Node next; private Node(E d, Node n){data=d; next=n;} } private Node head; public List() {head=null;} Nested class The first Node in the list

7 Nested class (aka. inner class)
A nested class is a member of its enclosing class. Non-static nested classes (inner classes) have access to other members of the enclosing class, even if they are declared private. Static nested classes do not have access to other members of the enclosing class. As a member of the OuterClass, a nested class can be declared private, public or protected.

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

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

10 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

11 Linked List implementation
private class MyIterator implements ListIterator<E> { private Node current; private MyIterator() {current=head;} public boolean hasNext() { return (current != null);} public E next() { E next = current.data; current = current.next; return a;} } public ListIterator<E> iterator() { return new MyIterator<E>(); Inner class Return an iterator for this list

12 Stack (reminder) 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

13 Queue (reminder) 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.

14 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

15 Enqueue to tail, dequeue from head
public class Queue<E> {     private List<E> head, tail;     public Queue<E>() { head = tail = null; }     public boolean isEmpty(){ return head == null; }     public void enqueue(E x) {                List<E> tmp = new List<E>(x, null);         if (tail!=null) tail.setNext(tmp);         tail = tmp;         if (head == null) head = tail;     }     public E dequeue(){         assert !isEmpty();         E x = head.getData();         head = head.getNext();         if (head == null) tail = null;              return x; }

16 What does this method assume?
removeLast (no tail) public E 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?

17 A doubly-linked list with a tail
public class List<E> { protected class Node { E data; Node next, prev; Node(E d, Node p, Node n) { data=d; prev=p; next=n; } protected Node head, tail; public List<E>() { head = tail = null;

18 A doubly-linked list with a tail
public void addFirst(E d) { Node<E> node = new Node<E>(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; }

19 A doubly-linked list with a tail
public E removeFirst() { E 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; What does this method assume?

20 A doubly-linked list with a tail
public E removeLast(){ E 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?

21 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: data 2 5 7 null count 1 3 2 21

22 CountIntList public class CountIntList { protected 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;} 22

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

24 Add the given data to the 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); }

25 We want a DB of students sorted by their grades in each subject
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

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

27 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];

28 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

29 Return the node which should come before the given student in list #i
Grades DB Return the node which should come before the given student in list #i 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;

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

31 Linked Lists vs. Arrays Operation Linked List Array Insert at head
Insert at middle O(n), O(1) given a reference Remove from head Remove from middle Find k-th element O(k) Search unsorted Search sorted O(log n)

32

33

34

35

36

37

38 Continue in next slide…

39

40


Download ppt "Tirgul 12 Data Structures (2) 1."

Similar presentations


Ads by Google