Functional Data Structures and Algorithms

Total Page:16

File Type:pdf, Size:1020Kb

Functional Data Structures and Algorithms Charles University in Prague Faculty of Mathematics and Physics DOCTORAL THESIS Milan Straka Functional Data Structures and Algorithms Computer Science Institute of Charles University Supervisor of the thesis: doc. Mgr. Zdeněk Dvořák, Ph.D. Study programme: Computer Science Specialization: Discrete Models and Algorithms (4I4) Prague 2013 I am grateful to Zdeněk Dvořák for his support. He was very accommodative during my studies. He quickly discovered any errors in my early conjectures and suggested areas of interest that prove rewarding. I would also like to express my sincere gratitude to Simon Peyton Jones for his supervision and guidance during my internship in Microsoft Research Labs, and also for helping me with one of my papers. Our discussions were always very intriguing and motivating. Johan Tibell supported my work on data structures in Haskell. His enthusiasm encouraged me to overcome initial hardships and continues to make the work really enjoyable. Furthermore, I would like to thank to Michal Koucký for comments and dis- cussions that improved the thesis presentation considerably. Finally, all this would not be possible without my beloved wife and my parents. You make me very happy, Jana. iii iv I declare that I carried out this doctoral thesis independently, and only with the cited sources, literature and other professional sources. I understand that my work relates to the rights and obligations under the Act No. 121/2000 Coll., the Copyright Act, as amended, in particular the fact that the Charles University in Prague has the right to conclude a license agreement on the use of this work as a school work pursuant to Section 60 paragraph 1 of the Copyright Act. In Prague, date 12th August 2013 ..................................................... signature of the author v vi Název práce: Funkcionální datové struktury a algoritmy Autor: Milan Straka Ústav: Informatický ústav Univerzity Karlovy Vedoucí doktorské práce: doc. Mgr. Zdeněk Dvořák, Ph.D, Informatický ústav Univerzity Karlovy Abstrakt: Funkcionální programování je rozšířené a stále více oblíbené programo- vací paradigma, které nachází své uplatnění i v průmyslových aplikacích. Datové struktury používané ve funkcionálních jazycích jsou převážně perzistentní, což znamená, že pokud jsou změněny, zachovávají své předchozí verze. Cílem této práce je rozšířit teorii perzistentních datových struktur a navrhnout efektivní implementace těchto datových struktur pro funkcionální jazyky. Bezpochyby nejpoužívanější datovou strukturou je pole. Ačkoli se jedná o velmi jednoduchou strukturu, neexistuje jeho perzistentní protějšek s konstantní složitostí přístupu k prvku. V této práci popíšeme zjednodušenou implementaci perzistentního pole s asymptoticky optimální amortizovanou časovou složitostí Θ(log log n) a především téměř optimální implementaci se složitostí v nejhorším případě. Také ukážeme, jak efektivně rozpoznat a uvolnit nepoužívané verze perzistentního pole. Nejvýkonnější datové struktury nemusí být vždy ty, které jsou založeny na asymptoticky nejlepších strukturách. Z toho důvodu se také zaměříme na imple- mentaci datových struktur v čistě funkcionálním programovacím jazyku Haskell a podstatně zlepšíme standardní knihovnu datových struktur jazyka Haskell. Klíčová slova: perzistentní datové struktury, perzistentní pole, algoritmy se složi- tostí v nejhorším případě, čistě funkcionální datové struktury, Haskell vii viii Title: Functional Data Structures and Algorithms Author: Milan Straka Institute: Computer Science Institute of Charles University Supervisor of the doctoral thesis: doc. Mgr. Zdeněk Dvořák, Ph.D, Computer Science Institute of Charles University Abstract: Functional programming is a well established programming paradigm and is becoming increasingly popular, even in industrial and commercial appli- cations. Data structures used in functional languages are principally persistent, that is, they preserve previous versions of themselves when modified. The goal of this work is to broaden the theory of persistent data structures and devise efficient implementations of data structures to be used in functional languages. Arrays are without any question the most frequently used data structure. Despite being conceptually very simple, no persistent array with constant time access operation exists. We describe a simplified implementation of a fully per- sistent array with asymptotically optimal amortized complexity Θ(log log n) and especially a nearly optimal worst-case implementation. Additionally, we show how to effectively perform a garbage collection on a persistent array. The most efficient data structures are not necessarily based on asymptotically best structures. On that account, we also focus on data structure implementations in the purely functional language Haskell and improve the standard Haskell data structure library considerably. Keywords: persistent data structures, persistent arrays, worst-case algorithms, purely functional data structures, Haskell ix x Contents 1 Introduction 1 1.1 Functionalprogramming . 1 1.2 PersistentDataStructures . 5 1.3 StructureoftheThesis ........................ 9 I Persistent Data Structures 13 2 Making Data Structures Persistent 15 2.1 PathCopyingMethod ........................ 17 2.2 Making Linked Structures Persistent . 18 2.3 Making Linked Structures Persistent in the Worst Case . .... 25 2.4 Making Amortized Structures Persistent . 29 3 Navigating the Version Tree 39 3.1 LinearizingtheVersionTree . 40 3.2 ListLabelling ............................. 40 3.3 ListOrderProblem.......................... 46 4 Dynamic Integer Sets 53 4.1 VanEmdeBoasTrees ........................ 54 4.2 ExponentialTrees........................... 58 5 Persistent Arrays 63 5.1 RelatedWork ............................. 65 5.2 Lower Bound on Persistent Array Lookup . 67 5.3 AmortizedPersistentArray . 69 5.4 Worst-CasePersistentArray . 74 5.5 Improving Complexity of Persistent Array Operations . ..... 76 5.6 Garbage Collection of a Persistent Array . 78 xi xii CONTENTS II Purely Functional Data Structures 85 6 Persistent Array Implementation 87 6.1 Fully Persistent Array Implementation . 87 6.2 Choosing the Best Branching Factor . 90 7 BB-ω Trees 95 7.1 BB-ω Trees .............................. 96 7.2 Rebalancing BB-ω Trees ....................... 99 7.3 Choosing the Parameters ω, α and δ ................ 101 7.4 BB-ω TreesHeight .......................... 106 7.5 Performance of BB-ω Trees ..................... 107 7.6 Reducing Memory by Utilizing Additional Data Constructor . 109 8 The Haskell containers Package 113 8.1 The containers Package ...................... 114 8.2 Benchmarks .............................. 117 8.3 Improving the containers Performance . 128 8.4 NewHashing-BasedContainer . 137 9 Conclusion 147 Bibliography 149 List of Terms and Abbreviations 159 List of Figures 161 Attachments 163 A.1 GeneratingFigure7.3 . 163 A.2 PackagesUsedinChapter8 . 164 Chapter 1 Introduction Computer programming has been developing enormously ever since the first high-level languages were created,1 and several fundamental approaches to com- puter programming, i.e., several programming paradigms, have been designed. The prevalent approach is the imperative programming paradigm, represented for example by the wide-spread C language. The imperative paradigm considers a computer program to be a sequence of statements that change the program state. In other words, serial orders (imper- atives) are given to the computer. The declarative programming represents a contrasting paradigm to the im- perative programming. The fundamental principle of declarative approach is describing the problem instead of defining the solution, allowing the program to express what should be accomplished instead of how should it be accomplished. The logic of the computation is described without dependence on control flow, as opposed to the imperative programing, where the control flow is a fundamental part of any program. One of the well established way of realizing the declarative paradigm is func- tional programming. 1.1 Functional programming Functional programming treats computations as evaluations of mathematic func- tions and the process of program execution is viewed as application of functions instead of changes in state. 1FORTRAN, “Formula Translator”, released in 1954, is considered the first high-level lan- guage with working implementation. 1 2 CHAPTER 1. INTRODUCTION Referential Transparency A major difference between functional and imperative programming is absence of side effects that change global program state. Function has a side effect, if, in addition to returning a value, it irreversibly modifies some global state or has an observable effect on the outside world, like displaying a message on a screen. Side effects are common in imperative programming, while in functional programming, output of a function depends solely on the input arguments and not on an internal state of a program. Therefore, calling a function twice with the same arguments produces the same result. Functional programs are referentially transparent, meaning that a function can be replaced by its resulting value without changing the behaviour of the program. The functional languages that completely lack the side effects are usually called purely functional and considered declarative. Because purely functional language does not define a specific evaluation order, various evaluation strategies are possible. One of the most theoretically and practically interesting strategies is lazy evaluation. Under
Recommended publications
  • Device Tree 101
    Device Tree 101 Device Tree 101 Organized in partnership with ST February 9, 2021 Thomas Petazzoni embedded Linux and kernel engineering [email protected] © Copyright 2004-2021, Bootlin. Creative Commons BY-SA 3.0 license. Corrections, suggestions, contributions and translations are welcome! - Kernel, drivers and embedded Linux - Development, consulting, training and support - https://bootlin.com 1/56 Who is speaking ? I Thomas Petazzoni I Chief Technical Officer at Bootlin I Joined in 2008, employee #1 I Embedded Linux & Linux kernel engineer, open-source contributor I Author of the Device Tree for Dummies talk in 2013/2014 I Buildroot co-maintainer I Linux kernel contributor: ≈ 900 contributions I Member of Embedded Linux Conference (Europe) program committee I Based in Toulouse, France - Kernel, drivers and embedded Linux - Development, consulting, training and support - https://bootlin.com 2/56 Agenda I Bootlin introduction I STM32MP1 introduction I Why the Device Tree ? I Basic Device Tree syntax I Device Tree inheritance I Device Tree specifications and bindings I Device Tree and Linux kernel drivers I Common properties and examples - Kernel, drivers and embedded Linux - Development, consulting, training and support - https://bootlin.com 3/56 Bootlin I In business since 2004 I Team based in France I Serving customers worldwide I 18% revenue from France I 44% revenue from EU except France I 38% revenue outside EU I Highly focused and recognized expertise I Embedded Linux I Linux kernel I Embedded Linux build systems I Activities
    [Show full text]
  • Slide Set 17 for ENCM 339 Fall 2015
    Slide Set 17 for ENCM 339 Fall 2015 Steve Norman, PhD, PEng Electrical & Computer Engineering Schulich School of Engineering University of Calgary Fall Term, 2015 SN's ENCM 339 Fall 2015 Slide Set 17 slide 2/46 Contents Data structures Abstract data types Linked data structures A singly-linked list type in C++ Operations and implementation of SLListV1 The Big 3 for a linked-list class Ordered linked lists SN's ENCM 339 Fall 2015 Slide Set 17 slide 3/46 Outline of Slide Set 17 Data structures Abstract data types Linked data structures A singly-linked list type in C++ Operations and implementation of SLListV1 The Big 3 for a linked-list class Ordered linked lists SN's ENCM 339 Fall 2015 Slide Set 17 slide 4/46 Data structures In discussion of programming, the term data structure means a collection of data items, organized to support some of the following goals: I fast insertion or removal of data items I fast access to data items I fast searching for the location of a particular data item, if the item is in the collection I maintaining items in some kind of sorted order I keeping the memory footprint of the collection as small as possible There are design trade-offs|no single data structure design is best for all of the above goals. SN's ENCM 339 Fall 2015 Slide Set 17 slide 5/46 Here are two kinds of data structures that everybody in this course should be familiar with: I arrays I C and C++ structure objects We're about to study a kind of data structure called a linked list.
    [Show full text]
  • Fast Sequential Summation Algorithms Using Augmented Data Structures
    Fast Sequential Summation Algorithms Using Augmented Data Structures Vadim Stadnik [email protected] Abstract This paper provides an introduction to the design of augmented data structures that offer an efficient representation of a mathematical sequence and fast sequential summation algorithms, which guarantee both logarithmic running time and logarithmic computational cost in terms of the total number of operations. In parallel summation algorithms, logarithmic running time is achieved by high linear computational cost with a linear number of processors. The important practical advantage of the fast sequential summation algorithms is that they do not require supercomputers and can run on the cheapest single processor systems. Layout 1. Motivation 2. Parallel Summation Algorithms 3. Choice of Data Structure 4. Geometric Interpretation 5. Representation of Sequence 6. Fast Sequential Summation Algorithms 7. Mean Value and Standard Deviation 8. Other Data Structures 1. Motivation The original version of the fast sequential summation algorithms described here was implemented in C++ using data structures that support interfaces of STL containers [1]. These interesting and important algorithms can be implemented in many other programming languages. This discussion provides an introduction to the design of data structures, which significantly improve performance of summation algorithms. The fast summation algorithms have been developed by applying the method of augmenting data structures [2]. This powerful method can be used to solve a wide range of problems. It helps design advanced data structures that support more efficient algorithms than basic data structures. The main disadvantage of this method is its complexity, which makes the use of this method difficult in practice.
    [Show full text]
  • Linked List Data Structure
    Linked List Data Structure Static and Dynamic data structures A static data structure is an organization of collection of data that is fixed in size. as memory ,(مسبقا") This results in the maximum size needing to be known in advance cannot be reallocated at a later. Arrays are example of static data structure. A dynamic data structure , where in with the latter the size of the structure can dynamically grow or shrink in size as needed. Linked lists are example of dynamic data structure. Linked Lists Like arrays, Linked List is a linear data structure. Unlike arrays, linked list elements are not stored at contiguous location; the elements are linked using pointers. It consists of group of nodes in a sequence which is divided in two parts. Each node consists of its own data and the address of the next node and forms a chain. Linked Lists are used to create trees and graphs. What are different between linked lists and arrays? Arrays Linked lists Have a pre-determined fixed No fixed size; grow one element at a time size Array items are store Element can be stored at any place contiguously Easy access to any element in No easy access to i-th element , need to hop through all previous constant time elements start from start Size = n x sizeof(element) Size = n x sizeof (element) + n x sizeof(reference) Insertion and deletion at Insertion and deletion are simple and faster particular position is complex(shifting) Only element store Each element must store element and pointer to next element (extra memory for storage pointer).
    [Show full text]
  • Arxiv:Submit/0396732
    Dynamic 3-sided Planar Range Queries with Expected Doubly Logarithmic Time⋆ Gerth Stølting Brodal1, Alexis C. Kaporis2, Apostolos N. Papadopoulos4, Spyros Sioutas3, Konstantinos Tsakalidis1, Kostas Tsichlas4 1 MADALGO⋆⋆, Department of Computer Science, Aarhus University, Denmark gerth,tsakalid @madalgo.au.dk 2 { } Computer Engineering and Informatics Department, University of Patras, Greece [email protected] 3 Department of Informatics, Ionian University, Corfu, Greece [email protected] 4 Department of Informatics, Aristotle University of Thessaloniki, Greece [email protected] Abstract. This work studies the problem of 2-dimensional searching for the 3-sided range query of the form [a,b] ( , c] in both main × −∞ and external memory, by considering a variety of input distributions. We present three sets of solutions each of which examines the 3-sided problem in both RAM and I/O model respectively. The presented data structures are deterministic and the expectation is with respect to the input distribution: (1) Under continuous µ-random distributions of the x and y coordinates, we present a dynamic linear main memory solution, which answers 3- sided queries in O(log n + t) worst case time and scales with O(log log n) expected with high probability update time, where n is the current num- ber of stored points and t is the size of the query output. We external- ize this solution, gaining O(logB n + t/B) worst case and O(logB logn) amortized expected with high probability I/Os for query and update operations respectively, where B is the disk block size. (2)Then, we assume that the inserted points have their x-coordinates drawn from a class of smooth distributions, whereas the y-coordinates are arbitrarily distributed.
    [Show full text]
  • Amortized Analysis
    Amortized Analysis Outline for Today ● Euler Tour Trees ● A quick bug fix from last time. ● Cartesian Trees Revisited ● Why could we construct them in time O(n)? ● Amortized Analysis ● Analyzing data structures over the long term. ● 2-3-4 Trees ● A better analysis of 2-3-4 tree insertions and deletions. Review from Last Time Dynamic Connectivity in Forests ● Consider the following special-case of the dynamic connectivity problem: Maintain an undirected forest G so that edges may be inserted an deleted and connectivity queries may be answered efficiently. ● Each deleted edge splits a tree in two; each added edge joins two trees and never closes a cycle. Dynamic Connectivity in Forests ● Goal: Support these three operations: ● link(u, v): Add in edge {u, v}. The assumption is that u and v are in separate trees. ● cut(u, v): Cut the edge {u, v}. The assumption is that the edge exists in the tree. ● is-connected(u, v): Return whether u and v are connected. ● The data structure we'll develop can perform these operations time O(log n) each. Euler Tours on Trees ● In general, trees do not have Euler tours. a b c d e f a c d b d f d c e c a ● Technique: replace each edge {u, v} with two edges (u, v) and (v, u). ● Resulting graph has an Euler tour. A Correction from Last Time The Bug ● The previous representation of Euler tour trees required us to store pointers to the first and last instance of each node in the tours.
    [Show full text]
  • Exponential Structures for Efficient Cache-Oblivious Algorithms
    Exponential Structures for Efficient Cache-Oblivious Algorithms Michael A. Bender1, Richard Cole2, and Rajeev Raman3 1 Computer Science Department, SUNY Stony Brook, Stony Brook, NY 11794, USA. [email protected]. 2 Computer Science Department, Courant Institute, New York University, New York, NY 10012, USA. [email protected]. 3 Department of Mathematics and Computer Science, University of Leicester, Leicester LE1 7RH, UK. [email protected] Abstract. We present cache-oblivious data structures based upon exponential structures. These data structures perform well on a hierarchical memory but do not depend on any parameters of the hierarchy, including the block sizes and number of blocks at each level. The problems we consider are searching, partial persistence and planar point location. On a hierarchical memory where data is transferred in blocks of size B, some of the results we achieve are: – We give a linear-space data structure for dynamic searching that supports searches and updates in optimal O(logB N) worst-case I/Os, eliminating amortization from the result of Bender, Demaine, and Farach-Colton (FOCS ’00). We also consider finger searches and updates and batched searches. – We support partially-persistent operations on an ordered set, namely, we allow searches in any previous version of the set and updates to the latest version of the set (an update creates a new version of the set). All operations take an optimal O(logB (m+N)) amortized I/Os, where N is the size of the version being searched/updated, and m is the number of versions. – We solve the planar point location problem in linear space, taking optimal O(logB N) I/Os for point location queries, where N is the number of line segments specifying the partition of the plane.
    [Show full text]
  • Trees • Binary Trees • Traversals of Trees • Template Method Pattern • Data
    TREES • trees • binary trees • traversals of trees • template method pattern • data structures for trees Trees 1 Trees •atree represents a hierarchy - organization structure of a corporation Electronics R’Us R&D Sales Purchasing Manufacturing Domestic International TV CD Tuner Canada S. America Overseas Africa Europe Asia Australia - table of contents of a book student guide overview grading environment programming support code exams homeworks programs Trees 2 Another Example • Unix or DOS/Windows file system /user/rt/courses/ cs016/ cs252/ grades grades homeworks/ programs/ projects/ hw1 hw2 hw3 pr1 pr2 pr3 papers/ demos/ buylow sellhigh market Trees 3 Terminology • A is the root node. • B is the parent of D and E. • C is the sibling of B • D and E are the children of B. • D, E, F, G, I are external nodes, or leaves. • A, B, C, H are internal nodes. • The depth (level) of E is 2 • The height of the tree is 3. • The degree of node B is 2. A B C D E F G H I Property: (# edges) = (#nodes) − 1 Trees 4 Binary Trees • Ordered tree: the children of each node are ordered. • Binary tree: ordered tree with all internal nodes of degree 2. • Recursive definition of binary tree: •Abinary tree is either -anexternal node (leaf), or -aninternal node (the root) and two binary trees (left subtree and right subtree) Trees 5 Examples of Binary Trees • arithmetic expression + × × + 5 4 + × + 7 2 3 + 2 8 1 + 4 6 ((((3 × (1 + (4 + 6))) + (2 + 8)) × 5) + ( 4 × (7 + 2))) •river Trees 6 Properties of Binary Trees •(# external nodes ) = (# internal nodes) + 1 •(#
    [Show full text]
  • Lecture Notes of CSCI5610 Advanced Data Structures
    Lecture Notes of CSCI5610 Advanced Data Structures Yufei Tao Department of Computer Science and Engineering Chinese University of Hong Kong July 17, 2020 Contents 1 Course Overview and Computation Models 4 2 The Binary Search Tree and the 2-3 Tree 7 2.1 The binary search tree . .7 2.2 The 2-3 tree . .9 2.3 Remarks . 13 3 Structures for Intervals 15 3.1 The interval tree . 15 3.2 The segment tree . 17 3.3 Remarks . 18 4 Structures for Points 20 4.1 The kd-tree . 20 4.2 A bootstrapping lemma . 22 4.3 The priority search tree . 24 4.4 The range tree . 27 4.5 Another range tree with better query time . 29 4.6 Pointer-machine structures . 30 4.7 Remarks . 31 5 Logarithmic Method and Global Rebuilding 33 5.1 Amortized update cost . 33 5.2 Decomposable problems . 34 5.3 The logarithmic method . 34 5.4 Fully dynamic kd-trees with global rebuilding . 37 5.5 Remarks . 39 6 Weight Balancing 41 6.1 BB[α]-trees . 41 6.2 Insertion . 42 6.3 Deletion . 42 6.4 Amortized analysis . 42 6.5 Dynamization with weight balancing . 43 6.6 Remarks . 44 1 CONTENTS 2 7 Partial Persistence 47 7.1 The potential method . 47 7.2 Partially persistent BST . 48 7.3 General pointer-machine structures . 52 7.4 Remarks . 52 8 Dynamic Perfect Hashing 54 8.1 Two random graph results . 54 8.2 Cuckoo hashing . 55 8.3 Analysis . 58 8.4 Remarks . 59 9 Binomial and Fibonacci Heaps 61 9.1 The binomial heap .
    [Show full text]
  • Verifying Linked Data Structure Implementations
    Verifying Linked Data Structure Implementations Karen Zee Viktor Kuncak Martin Rinard MIT CSAIL EPFL I&C MIT CSAIL Cambridge, MA Lausanne, Switzerland Cambridge, MA [email protected] viktor.kuncak@epfl.ch [email protected] Abstract equivalent conjunction of properties. By processing each conjunct separately, Jahob can use different provers to es- The Jahob program verification system leverages state of tablish different parts of the proof obligations. This is the art automated theorem provers, shape analysis, and de- possible thanks to formula approximation techniques[10] cision procedures to check that programs conform to their that create equivalent or semantically stronger formulas ac- specifications. By combining a rich specification language cepted by the specialized decision procedures. with a diverse collection of verification technologies, Jahob This paper presents our experience using the Jahob sys- makes it possible to verify complex properties of programs tem to obtain full correctness proofs for a collection of that manipulate linked data structures. We present our re- linked data structure implementations. Unlike systems that sults using Jahob to achieve full functional verification of a are designed to verify partial correctness properties, Jahob collection of linked data structures. verifies the full functional correctness of the data structure implementation. Not only do our results show that such full functional verification is feasible, the verified data struc- 1 Introduction tures and algorithms provide concrete examples that can help developers better understand how to achieve similar results in future efforts. Linked data structures such as lists, trees, graphs, and hash tables are pervasive in modern software systems. But because of phenomena such as aliasing and indirection, it 2 Example has been a challenge to develop automated reasoning sys- tems that are capable of proving important correctness prop- In this section we use a verified association list to demon- erties of such data structures.
    [Show full text]
  • Fundamental Data Structures Contents
    Fundamental Data Structures Contents 1 Introduction 1 1.1 Abstract data type ........................................... 1 1.1.1 Examples ........................................... 1 1.1.2 Introduction .......................................... 2 1.1.3 Defining an abstract data type ................................. 2 1.1.4 Advantages of abstract data typing .............................. 4 1.1.5 Typical operations ...................................... 4 1.1.6 Examples ........................................... 5 1.1.7 Implementation ........................................ 5 1.1.8 See also ............................................ 6 1.1.9 Notes ............................................. 6 1.1.10 References .......................................... 6 1.1.11 Further ............................................ 7 1.1.12 External links ......................................... 7 1.2 Data structure ............................................. 7 1.2.1 Overview ........................................... 7 1.2.2 Examples ........................................... 7 1.2.3 Language support ....................................... 8 1.2.4 See also ............................................ 8 1.2.5 References .......................................... 8 1.2.6 Further reading ........................................ 8 1.2.7 External links ......................................... 9 1.3 Analysis of algorithms ......................................... 9 1.3.1 Cost models ......................................... 9 1.3.2 Run-time analysis
    [Show full text]
  • 8.1 Doubly Linked List
    CMSC 132, Object-Oriented Programming II Summer 2017 Lecture 8: Lecturer: Anwar Mamat Disclaimer: These notes may be distributed outside this class only with the permission of the Instructor. 8.1 Doubly Linked List Like a singly linked list, a doubly-linked list is a linked data structure that consists of a set of sequentially linked records called nodes. Unlike a singly linked list, each node of the doubly singly list contains two fields that are references to the previous and to the next node in the sequence of nodes. The beginning and ending nodes' previous and next links, respectively, point to some kind of terminator, typically a sentinel node or null, to facilitate traversal of the list. Listing 1: Doubly Linked List Node Class 1 class Node<E>{ 2 E data; 3 Node previous; 4 Node next; 5 Node(E item){ 6 data = item; 7 } 8 } Usually Node class is nested inside the LinkedList class, and members of Node are private. 8.1.1 Create a simple linked list Now, let us create a simple linked list. 1 Node<String> n1 = new Node("Alice"); 2 Node<String> n2 = new Node("Bob"); 3 Node<String> n3 = new Node("Cathy"); 4 n1.next = n2; 5 n2.previous = n1; 6 n2.next = n3; 7 n3.previous = n2; This linked list represents this: Alice Bob Cathy 8.1.2 Display the Linked List We can display all the linked list: 8-1 8-2 Lecture 8: 1 Node<String> current = first; 2 while(current != null){ 3 System.out.println(current.data); 4 current = current.next; 5 } We can also display all the linked list in reverse order: 1 Node<String> current = tail; 2 while(current != null){ 3 System.out.println(current.data); 4 current = current.previous; 5 } 8.1.3 Insert a node Now, let us insert a node between \Bob" and \Cathy".
    [Show full text]