VIEWS: 0 PAGES: 40 CATEGORY: Politics & History POSTED ON: 6/1/2010 Public Domain
IN2002 Data Structures and Algorithms Lecture 5 / Slide 1 MODULE IN2002 DATA STRUCTURES AND ALGORITHMS Lecture 5 Lecturer: Tillman Weyde t.e.weyde@city.ac.uk IN2002 Data Structures and Algorithms Lecture 5 / Slide 2 Coursework Available online: • Many questions and answers • Corrected version of the coursework sheet IN2002 Data Structures and Algorithms Lecture 5 / Slide 3 Lecture 5: SINGLY LINKED LISTS • Data structures: – Stacks – Vectors – Singly linked lists • Algorithms: – Adding elements – Extracting elements IN2002 Data Structures and Algorithms Lecture 5 / Slide 4 RECORDS • A record is a fixed collection of things of different types. • EG records at a mobile phone provider: Client ID 1234 Phone number +44 7887 4444444 Owner Rupert Taylor Start date 04/10/2001 Credit £24.53 Type of contract Ultra International opt. No Free minutes left 42 IN2002 Data Structures and Algorithms Lecture 5 / Slide 5 Records as objects class Mobile { public int clientID; public String number; public String name; public Date startdate; public int credit; public char contract; public boolean intl; public int seconds; ... public Mobile(int id, String nu, String na, ...) { clientID = c; number = nu; name = na; .... } } IN2002 Data Structures and Algorithms Lecture 5 / Slide 6 Pointers to records • In Java, variables cannot contain objects (record instances, in this case), but pointers to them • Every reference type can have value null, which refers to no object at all Mobile x = null; • Several variables may refer to the same object: Mobile y = new Mobile(1234, “+44 7887 4444444”,“Rupert”,...); Mobile z = y; IN2002 Data Structures and Algorithms Lecture 5 / Slide 7 Are two records equal? Consider: Mobile x = new Mobile(1234, “+44 7887 4444444”,“Rupert”,...); Mobile y = new Mobile(1234, “+44 7887 4444444”,“Rupert”,...); Mobile z = x; x == z is TRUE x == y is FALSE because y is not the same object created for x, but a new one x.compareTo(y), however, can be defined to return 0 to indicate that both objects contain the same values IN2002 Data Structures and Algorithms Lecture 5 / Slide 8 Sorting records In the coursework you are asked to define a compareTo method for sorting. Necessary for sorting: sorting criterion must define a total order.: if a ≤ b and b ≤ a then a = b (antisymmetry, ) if a ≤ b and b ≤ c then a ≤ c (transitivity) a ≤ b or b ≤ a (totalness) IN2002 Data Structures and Algorithms Lecture 5 / Slide 9 DYNAMIC DATA STRUCTURES • Many data structures vary in size in an undetermined way • Reallocate-and-copy of arrays can solve this problem • In general, linked structures are more flexible: – singly linked lists – doubly linked lists and circular lists – trees and graphs IN2002 Data Structures and Algorithms Lecture 5 / Slide 10 Queues First In First Out (FIFO) • As opposed to last in first out (stacks, heaps) • And also to priority queues (in which priorities may not reflect the actual order of addition) IN2002 Data Structures and Algorithms Lecture 5 / Slide 11 A queue ADT public interface Queue { // Is the queue empty? boolean isEmpty(); // Add an element to the queue void enqueue(int elt); // Remove and return the earliest element of // the queue int dequeue(); } IN2002 Data Structures and Algorithms Lecture 5 / Slide 12 A stack ADT // a stack of integers public interface Stack { // is the stack empty? boolean isEmpty(); // add (push) an element into the stack void push(int elt); // remove and return the most recently pushed // element still in the stack int pop(); } IN2002 Data Structures and Algorithms Lecture 5 / Slide 13 Extending arrays by Relocate-and-copy • Because size is unpredictable: – initial array allocation may fall short – trying to be safe is wasteful • A solution: extensible arrays – start with a small array – if more space is needed, create a new, larger array and copy elements to it ... adds O(n) to space and O(n) to time IN2002 Data Structures and Algorithms Lecture 5 / Slide 14 Stacks with relocate-and-copy public class ArrayStack implements Stack { private int count = 0; private int[] data = new int[1]; public boolean isEmpty() { return count == 0; } public int pop() { count--; return data[count]; } ... continues IN2002 Data Structures and Algorithms Lecture 5 / Slide 15 Stacks with relocate-and-copy (ctd.) ... which was the same as last week. However: public void push(int elt) { if (count == data.length) { // not enough space int[] new = new int[data.length + 1]; // new for (i = 0; i < count; i++) // array new[i] = data[i]; // copy elements data = new; // set new array } data[count] = elt; // add new element count++; } } IN2002 Data Structures and Algorithms Lecture 5 / Slide 16 Analysis of the implementation In a sequence of n pushes, the number of copies is 1 + 2 + 3 + ... + (n - 1) = n(n - 1)/2 = O(n2) Going up by a larger step than 1 improves things, but only by a constant factor. IN2002 Data Structures and Algorithms Lecture 5 / Slide 17 ... an improvement If we double the size whenever it overgrows, the number of element copies for n = 2k-1 pushes is 1 + 2 + 22 + ... + 2k-1 = 2k - 1 = O(n) This averages out at O(1) per operation: the cost is amortised over the sequence of operations In some cases you may want (or need) to free space using the opposite procedure IN2002 Data Structures and Algorithms Lecture 5 / Slide 18 Proof: Sum of Powers of 2 This has been used in the last analysis and the telescopic sum. Statement: 1 + 2 + 22 + ... + 2k-1 = 2k - 1 Proof by in induction: base case k=2: 20 + 21 = 1 + 2 = 3 = 4 – 1 = 22 – 1 step k to k+1: 20 + ... 2k-1 + 2k = 2k – 1 + 2k = 2·2k – 1 = 2k+1 – 1 IN2002 Data Structures and Algorithms Lecture 5 / Slide 19 Array-like operations in extensible arrays Some O(1) time operations in extensible arrays: public int size() { return count; } public int elementAt(int pos) { return data[pos]; } public void setElementAt(int pos, int value) { data[pos] = value; } IN2002 Data Structures and Algorithms Lecture 5 / Slide 20 Summary of extensible arrays • Extensible arrays are an implementation of the Stack ADT that use O(n) space • With the right extension policy, these operations take O(1) time • They also provide array-like operations at O(1) time • Implementing the Queue ADT with extensible arrays is not so convenient • For greater convenience, we can use pointers IN2002 Data Structures and Algorithms Lecture 5 / Slide 21 SINGLY LINKED LISTS How do you remove a value from the middle of an array? How would you do it in real life, e.g. in a long written list? In real life, to add something at the middle of a long list what do you do? How would you do it with arrays? Singly linked lists use pointers as links to the next element in the list IN2002 Data Structures and Algorithms Lecture 5 / Slide 22 Nodes in singly linked lists Each node contains a value and a pointer to the next node: public class Node { info public int info; next public Node next; ... } Node h; 5 8 3 null IN2002 Data Structures and Algorithms Lecture 5 / Slide 23 A node implementation in a singly linked list public class Node { public int info; public Node next; public Node(int i, Node n) { info = i; next = n; } public Node(int i) { this(i, null); } } IN2002 Data Structures and Algorithms Lecture 5 / Slide 24 Adding elements at the head of a list Node h Node h = null; null Node h 3 h = new Node(3); null Node h h = new Node(8,h); 8 3 null h = new Node(5,h); Node h 5 8 3 null IN2002 Data Structures and Algorithms Lecture 5 / Slide 25 Adding elements at the tail Node h Node h = null; null Node h 5 h = new Node(5); null Node h h.next = 5 8 new Node(8); null h.next.next = Node h new Node(3); 5 8 3 null IN2002 Data Structures and Algorithms Lecture 5 / Slide 26 Pointers to the head and tail Adding elements at the tail is faster if we keep a pointer to the last element (if any). We define a new class to hold the head and tail pointers: SLList Node head; Node tail; 5 8 3 null IN2002 Data Structures and Algorithms Lecture 5 / Slide 27 The singly linked list class public class SLList { private Node head = null; private Node tail = null; public boolean isEmpty() { return head == null; } public void addToHead(int el) {...} public void addToTail(int el) { ... } public int deleteFromHead() {...} } IN2002 Data Structures and Algorithms Lecture 5 / Slide 28 Special cases An empty list: SLList Node head; null Node tail; null A list with one element: SLList Node head; Node tail; 5 null IN2002 Data Structures and Algorithms Lecture 5 / Slide 29 What shouldn’t happen in singly linked lists • Loops • Errors with pointers tail does not point to head.next. ... .next • Tail node with non-null pointer • Non-tail node with null pointer IN2002 Data Structures and Algorithms Lecture 5 / Slide 30 OPERATIONS IN SINGLY LINKED LISTS • Adding an element at the head • Adding an element at the tail • Deleting the head element • Deleting the tail element IN2002 Data Structures and Algorithms Lecture 5 / Slide 31 Adding an element at the head There are two cases: - The list contains at least one element (so the tail stays the same) - The list is empty (head = tail = null) (we need to set the tail) public void addToHead(int el) { head = new Node(el, head); if(tail == null) tail = head; } IN2002 Data Structures and Algorithms Lecture 5 / Slide 32 Adding an element at the tail Two cases again: - If the list is empty, we need to set the head - Otherwise, we need to set the pointer of the old tail public void addToTail(int el) { if (! isEmpty()) { tail.next = new Node(el); tail = tail.next; } else head = tail = new Node(el); } IN2002 Data Structures and Algorithms Lecture 5 / Slide 33 Deleting the head element SLList Node head; Node tail; Just move the 5 8 3 head pointer: null SLList (Special case: Node head; head == tail Node tail; -> head = null; 5 8 3 tail = null;) null IN2002 Data Structures and Algorithms Lecture 5 / Slide 34 Deleting the head element (2) If the list has more than one elements, change the head Otherwise, make the list empty public int deleteFromHead() { int el = head.info; if(head == tail) \\ one or no elements head = tail = null; else head = head.next; return el; } IN2002 Data Structures and Algorithms Lecture 5 / Slide 35 Deleting the last element We need to set tail to the second last node ... but it's more easily said than done: to find it we need to scan the whole list ! O(n) IN2002 Data Structures and Algorithms Lecture 5 / Slide 36 Traversing a list Function printList(): node1 ← head of list WHILE node1 is not null print value of node1 node1 ← next of node1 ... so to traverse the list, iteratively (or recursively!) evaluate the rest of the list (i.e. next) IN2002 Data Structures and Algorithms Lecture 5 / Slide 37 Applications of singly linked lists • A list requires O(n) space • The operations we have defined each take O(1) time • Lists can represent the following ADTs: • Stack uses addToHead for push, and deleteFromHead for pop • Queue uses addToTail for enqueue, and deleteFromHead to dequeue • Lists may also be used directly in many algorithms • Important high-level programming languages strongly rely on linked lists (e.g., Lisp) IN2002 Data Structures and Algorithms Lecture 5 / Slide 38 Other uses? It is possible to implement priority queues, stacks and heaps using linked lists. However, is this efficient? Let us have a closer look: • priority queues: inserting a new element in a sorted linked list takes O(n) • heaps: searching a parent or child in a linked list is O(n) IN2002 Data Structures and Algorithms Lecture 5 / Slide 39 Summary of singly linked lists • Extensible arrays efficiently implement the Stack ADT, as well as the array operations, overhead for additional space • Singly linked lists efficiently implement the Stack and Queue ADTs, and have many other uses • Singly linked lists can only move in one direction accessing elements in the middle or rear part is difficult • Overhead for the pointers IN2002 Data Structures and Algorithms Lecture 5 / Slide 40 NEXT SESSION AND READING Next session (Week 7): Circular and doubly linked lists • Drozdek – This session: sections 1.4, 3.1 and 4.1 – Next week: sections 1.5, 3.2 and 3.3 ... or … • Weiss – This session: sections 2.1, 2.2, 6.6.1, 6.6.2, 17.1 and 17.2 – Next week: sections 6.5, 17.3