NotToBrag
NotToBrag

Reputation: 665

Add Nodes to Circular Doubly Linked List in Java

I've attempted to create and print a Circular Doubly Linked List that would contain nodes that hold values for every letter of the alphabet.

Here is my code so far:

CircularDoublyList.java

public static void main(String[] args) 
{
    CDLL<Character> head = null;
    CDLL<Character> tail = null;

    CDLL <Character> p = null; 
    for(char c = 'A'; c <= 'Z'; c++) {
        p = new CDLL<Character>(c, null, null);        
        if (head == null)
        {
            p.setNext(p);
            p.setPrevious(p);
            head = p;
            tail = head;
        }
        else
        {
            p.setPrevious(tail);
            tail.setNext(p);
            head.setPrevious(p);
            p.setNext(head);
            head = p;    
        }
    }

    print(p); 
}

public static void print(CDLL<Character> list) {
    String str = "";
    while(list != null) {
        str += list.getPrevious().getValue() + " ";         
        list = list.getPrevious();
    }
    System.out.print(str);
}

Issue: I've tried printing the list, but nothing seems to show up and their are no error message in the console. Any help would be appreciated.

Upvotes: 0

Views: 570

Answers (1)

Mike Laren
Mike Laren

Reputation: 8178

Well, because the list is circular, the code:

while(list != null) {
    str += list.getPrevious().getValue() + " ";         
    list = list.getPrevious();
}

will continue going in circles and will never stop.

Just change your method to stop when it finds the first node again:

public static void print(CDLL<Character> list) {
  String str = "";
  CDLL<Character> first = null;
  while (true) {
    str += list.getPrevious().getValue() + " ";
    if (first == null) 
       first = list.getPrevious();
    else if (first == list.getPrevious())
       break;
    list = list.getPrevious();
  }
  System.out.print(str);
}

Upvotes: 2

Related Questions