Part-B3 Linked Lists Linked Lists 1 Singly Linked List (§ 4.4.1) A singly linked list is a concrete data structure consisting of a sequence of nodes Each node stores next element link to the next node node elem A B C Linked Lists D 2 The Node Class for List Nodes public class Node { // Instance variables: private Object element; private Node next; /** Creates a node with null references to its element and next node. */ public Node() { this(null, null); } /** Creates a node with the given element and next node. */ public Node(Object e, Node n) { element = e; next = n; } // Accessor methods: public Object getElement() { return element; } public Node getNext() { return next; } // Modifier methods: public void setElement(Object newElem) { element = newElem; } public void setNext(Node newNext) { next = newNext; } } Linked Lists 3 Inserting at the Head 1. Allocate a new node 2. update new element 3. Have new node point to old head 4. Update head to point to new node Linked Lists 4 Removing at the Head 1. Update head to point to next node in the list 2. Allow garbage collector to reclaim the former first node Linked Lists 5 Inserting at the Tail 1. Allocate a new 2. 3. 4. 5. node Insert new element Have new node point to null Have old last node point to new node Update tail to point to new node Linked Lists 6 Removing at the Tail Removing at the tail of a singly linked list is not efficient! There is no constant-time way to update the tail to point to the previous node Linked Lists 7 Stack with a Singly Linked List We can implement a stack with a singly linked list The top element is stored at the first node of the list The space used is O(n) and each operation of the Stack ADT takes O(1) time nodes t elements Linked Lists 8 Queue with a Singly Linked List We can implement a queue with a singly linked list The front element is stored at the first node The rear element is stored at the last node The space used is O(n) and each operation of the Queue ADT takes O(1) time r nodes f elements Linked Lists 9 List ADT (§ 5.2.3) The List ADT models a sequence of positions storing arbitrary objects It establishes a before/after relation between positions Generic methods: Accessor methods: Update methods: size(), isEmpty() Linked Lists first(), last() prev(p), next(p) replace(p, e) insertBefore(p, e), insertAfter(p, e), insertFirst(e), insertLast(e) remove(p) 10 Doubly Linked List A doubly linked list provides a natural implementation of the List ADT Nodes implement Position and store: element link to the previous node link to the next node prev next elem node Special trailer and header nodes nodes/positions header trailer elements Linked Lists 11 Insertion We visualize operation insertAfter(p, X), which returns position q p A B C p A q B C X p A q B Linked Lists X C 12 Insertion Algorithm Algorithm insertAfter(p,e): Create a new node v v.setElement(e) v.setPrev(p) {link v to its predecessor} v.setNext(p.getNext()) {link v to its successor} (p.getNext()).setPrev(v) {link p’s old successor to v} p.setNext(v) {link p to its new successor, v} return v {the position for the element e} Linked Lists 13 Deletion We visualize remove(p), where p = last() p A B C A B C D p D A B Linked Lists C 14 Deletion Algorithm Algorithm remove(p): t = p.element {a temporary variable to hold the return value} (p.getPrev()).setNext(p.getNext()) {linking out p} (p.getNext()).setPrev(p.getPrev()) p.setPrev(null) {invalidating the position p} p.setNext(null) return t Linked Lists 15 Performance In the implementation of the List ADT by means of a doubly linked list The space used by a list with n elements is O(n) The space used by each position of the list is O(1) All the operations of the List ADT run in O(1) time Operation element() of the Position ADT runs in O(1) time Linked Lists 16 Terminologies A Graph G=(V,E): V---set of vertices and E--set of edges. Path in G: sequence v1, v2, ..., vk of vertices in V such that (vi, vi+1) is in E. vi and vj could be the same Simple path in G: a sequence v1, v2, ..., vk of distinct vertices in V such that (vi, vi+1) is in E. vi and vj can not be the same Linked Lists 17 Example: Simple path A path, but not simple Linked Lists 18 Terminologies (continued) Circuit: A path v1, v2, ..., vk such that v1 = vk . Simple circuit: a circuit v1, v2, ..., vk,where v1=vk and vivj for any 1<i, j<k. Linked Lists 19 Euler circuit Input: a graph G=(V, E) Problem: is there a circuit in G that uses each edge exactly once. Note: G can have multiple edges, .i.e., two or more edges connect vertices u and v. Linked Lists 20 Story: The problem is called Konigsberg bridge problem it asks if it is possible to take a walk in the town shown in Figure 1 (a) crossing each bridge exactly once and returning home. solved by Leonhard Euler [pronounced OIL-er] (1736) The first problem solved by using graph theory A graph is constructed to describe the town. (See Figure 1 (b).) Linked Lists 21 The original Konigsberg bridge Linked Lists (Figure 1) 22 Theorem for Euler circuit (proof is not required) Theorem 1 (Euler’s Theorem) The graph has an Euler circuit if and only if all the vertices of a connected graph have even degree. Proof: (if) Going through the circuit, each time a vertex is visited, the degree is increased by 2. Thus, the degree of each vertex is Linked even. Lists 23 Proof of Theorem 1: (only if) We give way to find an Euler circuit for a graph in which every vertex has an even degree. Since each node v has even degree, when we first enter v, there is an unused edge that can be used to get out v. The only exception is when v is a starting node. Then we get a circuit (may not contain all edges in G) If every node in the circuit has no unused edge, all the edges in G have been used since G is connected. Otherwise, we can construct another circuit, merge the two circuits and get a larger circuit. In this way, every edge in G can be used. Linked Lists 24 An example for Theorem 1: a a 13 2 1 b 11 8 3 10 g c e f 12 c 7 d 3 1 a 9 4 7 b b 4 d 7 6 2 1 c f 2 b d 5 f 6 i e after merge 3 4 e e c h 5 13 12 g 8 11 6 j 5 h i 10 9 j Linked Lists 25 An efficient algorithm for Euler circuit 1. Starting with any vertex u in G, take an unused edge (u,v) (if there is any) incident to u 2. Do Step 1 for v and continue the process until v has no unused edge. (a circuit C is obtained) 3. If every node in C has no unused edge, stop. 4. Otherwise, select a vertex, say, u in C, with some unused edge incident to u and do Steps 1 and 2 until another circuit is obtained. 5. Merge the two circuits obtained to form one circuit 6. Continue the above process until every edge in G is used. Linked Lists 26 Euler Path A path which contains all edges in a graph G is called an Euler path of G. Corollary: A graph G=(V,E) which has an Euler path has 2 vertices of odd degree. Linked Lists 27 Proof of the Corollary Suppose that a graph which has an Euler path starting at u and ending at v, where uv. Creating a new edge e joining u and v, we have an Euler circuit for the new graph G’=(V, E{e}). From Theorem 1, all the vertices in G’ have even degree. Remove e. Then u and v are the only vertices of odd degree in G. (Nice argument, not required for exam.) Linked Lists 28 Representations of Graphs Two standard ways Adjacency-list representation Adjacency-matrix representation Space required O(|E|) Space required O(n2). Depending on problems, both representations are useful. Linked Lists 29 Adjacency-list representation 1 Let G=(V, E) be a graph. V– set of nodes (vertices) E– set of edges. For each uV, the adjacency list Adj[u] contains all nodes in V that are adjacent to u. 2 3 5 4 1 2 5 2 1 5 3 2 4 4 2 5 3 / 5 4 1 2 / (a) / 3 4 / / (b) Linked Lists 30 Adjacency-matrix representation Assume that the nodes are numbered 1, 2, …, n. The adjacency-matrix consists of a |V||V| matrix A=(aij) such that 1 2 3 4 5 1 0 1 0 0 1 2 1 0 1 1 1 3 0 1 0 1 0 4 0 1 1 0 1 5 1 1 0 1 0 aij= 1 if (i,j) E, otherwise aij= 0. 2 1 3 5 4 (a) (c) Linked Lists 31 Implementation of Euler circuit algorithm (Not required) Data structures: Adjacency matrix Also, we have two lists to store the circuits One for the circuit produced in Steps 1-2. One for the circuit produced in Step 4 We can merge the two lists in O(n) time. In Step 1: when we take an unused edge (u, v), this edge is deleted from the adjacency matrix. Linked Lists 32 Implementation of Euler circuit algorithm In Step 2: if all cells in the column and row of v is 0, v has no unused edge. 1. Testing whether v has no unused edge. 2. A circuit (may not contain all edges) is obtained if the above condition is true. In Step 3: if all the element’s in the matrix are 0, stop. In step 4: if some elements in the matrix is not 0, continue. Linked Lists 33 Summary of Euler circuit algorithm Design a good algorithm needs two parts 1. Theorem, high level part 2. Implementation: low level part. Data structures are important. We will emphasize both parts. Linked Lists 34 Summary Understand singly linked list How to create a list insert at head, insert at tail, remove at head and remove at tail. Should be able to write program using singly linked list We will have chance to practice this. Know the concept of doubly linked list. No time to write program about this. Euler Circuit Understand the ideas No need for the implementation. Linked Lists 35 My Questions: (not part of the lecture) Have you learn recursive call? A function can call itself. . Example: f(n)=n!=n×(n-1)×(n-2)×…×2×1 and 0!=1. It can also be written as f(n)=n×f(n-1) and f(0)=1. Java code: Public static int recursiveFactorial(int n) { if (n==0) return 1; else return n*recursiveFactorial(n-1); } Linked Lists 36 Remks Delete Euler Circuit They do not like programming, especially, complicated programming work. Linked Lists 37