A circular linked list is a linked list where all nodes are connected to form a circle. (refer: https://www.geeksforgeeks.org/circular-linked-list/). Implement a class DoublyCircularLL implementing a circular linked list to make the following output.
public class DCLTest {
public static void main(String[] args) {
DoublyCircularLL< Integer> dcl = new DoublyCircularLL< Integer>();
dcl.add(5);
System.out.println(dcl);
dcl.insert(4);
System.out.println(dcl);
dcl.add(7);
System.out.println(dcl);
dcl.add(8);
System.out.println(dcl);
dcl.insert(3);
System.out.println(dcl);
dcl.insert(2);
System.out.println(dcl);
}
}
Output:
5 and < reverse> 5
4 5 and < reverse> 5 4
4 5 7 and < reverse> 7 5 4
4 5 7 8 and < reverse> 8 7 5 4
3 4 5 7 8 and < reverse> 8 7 5 4 3
2 3 4 5 7 8 and < reverse> 8 7 5 4 3 2
Starter Code
public class DoublyCircularLL< T> {
Node< T> start;
class Node< T> {
T data;
Node< T> prev, next;
public Node(T d, Node< T> p, Node< T> n) {
data = d;prev=p; next=n;
}
public Node(T d) {
data=d; prev=next=this;
}
}
// add a new node at the end
public void add(T d) {
// If the list is empty, create a single node
if(start == null) {
start = new Node(d);
} else {
// If the list is not empty, find the last node
Node< T> last = start.prev;
// create node
last.next = new Node< T>(__________);
// set the prev node of the start
__________;
}
}
// insert at the beginning
public void insert(T d) {
// If the list is empty, create a single node
if(start == null) {
start = new Node(d);
} else {
// If the list is not empty, find the last node
Node< T> last = start.prev;
// create node
last.next = new Node< T>(__________);
// set the next node of the start
start = __________;
}
}
public String toString() {
String s = "";
Node p = start;
while(p.next != start) {
s += p.data + " ";
p = p.next;
}
s += p.data + " ";
s += "and < reverse> ";
p = __________;
while(__________) {
s += p.data + " ";
p = p.prev;
}
s += p.data + " ";
return s;
}
}