80 likes | 149 Views
CSC 205 Programming II. Linked List – Other Variations. The First Node – a special case. Add to or delete from index = 1 is special You don’t have to find first!. Node newNode = new Node(nObj, head); head = newNode;. obj1. head. nObj. inserted item. obj1. obj2. head.
E N D
CSC 205 Programming II Linked List – Other Variations
The First Node – a special case • Add to or delete from index = 1 is special • You don’t have to find first! Node newNode = new Node(nObj, head); head = newNode; obj1 head nObj inserted item obj1 obj2 head deleted item head = head.getNext();
Write a Linked List Backward • Two recursive strategies • writeListBackward: • Write the last node • Write the list minus its last node backward • writeListBackward2: • Write the list minus its first node backward • Write the first node obj1 obj2 obj1 obj2 head item next null head item next null writeListBackward writeListBackward2
Which One Is More Efficient? • writeListBackward2! • There is no efficient ways to get the last node • There is no efficient ways to get the list minus the last node void writeListBackward2(Node nextNode) { if (nextNode != null) { writeListBackward2(nextNode.getNext()); //write the first node System.out.println(nextNode.getItem()); } }
Variations • The normal version • (singly) linked list (with a head reference) • Other variations • Circular linked list • Doubly linked list with both head and tail references • Circular doubly linked list
Circular Linked List • The last node has its next referencing the first node (head) in the list … obj1 obj2 obj3 objx head //display contents in a circular linked list if (head != null) { Node curr = head; do { System.out.println(curr.getItem()); curr = curr.getNext(); } while (curr != head) }
Doubly Linked List • A node has a reference to its successor and one to the node precedes it • Node(Object item, Node next, Node precede) … obj1 obj2 objx head
Circular Doubly Linked List • The one implemented in the java.util package … obj1 obj2 objx head