Algorithms and OOD (CSC 207 2013F) : EBoards

CSC207.01 2013F, Class 29: Doubly-Linked Lists


Overview

Admin

Review of singly-linked lists

Insertion and deletion in singly-linked lists

Prepend

public void prepend(T val) {
    // Create a new node, with T as a val and front as next
   Node<T> newfront = new Node(T, this.front);
   this.front = newfront;
} // prepend(T)

public void prepend(T val) {
    // Create a new node, with T as a val and front as next
   this.front = new Node(T, this.front);
} // prepend(T)

Two strategies:

Code, revisited

Node<T> front;
Node<T> back;

public void prepend(T val) {
    // Create a new node, with T as a val and front as next
   this.front = new Node(T, this.front);
} // prepend(T)

public void append(T val) {
    // Create a new node with val and no successor
    // Update the former back of the list to make this new node the next node
    this.back.next =  new Node(T, null);
    // Update our notion of the back of the list
    this.back = this.back.next;
} // append(T)

What do we initialize front and back to for an empty list?

Worrying about special cases in linked lists is really important! (Was it empty? for insert; Will it be empty? for delete)

A trick for simplifying insertion and deletion

On to insert and delete with a cursor

public class LinkedListCursor<T> implements Cursor {

} // LinkedListCursor<T>

Add after current element is easy, delete current element is hard

Deletion

cursor.prev.next = cursor.prev.next.next;

A problem: How do we delete the first element, and where is cursor.prev when we start?

Doubly-linked lists

Twice the links! Twice the fun! Twice the potential for errors.

Circularly-linked lists

Dummy node with link to front and back

Copyright (c) 2013 Samuel A. Rebelsky.

Creative Commons License

This work is licensed under a Creative Commons Attribution 3.0 Unported License. To view a copy of this license, visit http://creativecommons.org/licenses/by/3.0/ or send a letter to Creative Commons, 543 Howard Street, 5th Floor, San Francisco, California, 94105, USA.