Reputation: 87
i am trying to write a generic circular linked list class. i tried to add nodes to the make a circular linked list but the adding of the nodes is not quit working correctly.. The order of the nodes being added is not correct for some strange reason..
import java.util.NoSuchElementException;
import linear.Node;
public class CircularLinkedList<T> {
/**
* @param args
*/
private Node<T> rear;
private static int size;
public CircularLinkedList() {
rear = null;
size = 0;
}
public void add(T data) {
rear = new Node<T>(data, rear);
size++;
}
}
public class Node<T> { //generic node
public T data;
public Node<T> next;
public Node(T data, Node<T> next) {
this.data = data;
this.next = next;
}
public String toString() {
return "" + data; //force concatation data.toString() is automatically called
}
}
Upvotes: 1
Views: 2987
Reputation: 246
By
rear = new Node<T>(data, rear);
you insert a node at the beginning of a linked list. The rear is pointing at the first node. Your problem is that the last node didn't point to the first node. I think it's better if you use 2 pointer here, one points to the beginning, and the other points to the end. And then, every time when you add a new node, not just let the first pointer point to the new node, but also let the end node points to the new beginning node.
private Node<T> head = null;
private Node<T> rear = null;
public void add(T data) {
head = new Node<T>(data, head);
if(rear == null)
rear = head;
rear.setNext(head);
size++;
}
This solution also insert new node at the beginning of the list. If you want to insert new node at the end of the list, you should do this:
private Node<T> head = null;
private Node<T> rear = null;
public void add(T data) {
Node<T> node = new Node<T>(data,head);
if(head == null){
head = node;
node.setNext(head);
}
if(rear != null)
rear.setNext(node);
rear = node;
size++;
}
Upvotes: 1
Reputation: 25666
21 and 2 is the correct answer. rear
is the first element of the linked list, and rear.next
is the second element. Since you added 21 last, it's the first element, and since you added 2 second-to-last, it's the second element.
Were you expecting something different?
Upvotes: 1