Adding tail node to a doubly linked list
The program works when I'm adding head nodes, so I thought it should be similar for the tail nodes, but it's been giving me problems. Here's the code for my node class and a section of the doubly linked list.
Code:
public class Node {
private int digit;
private Node previous;
private Node next;
public Node() {
digit = 0;
previous = null;
next = null;
}
public Node(int num, Node prev, Node next) {
digit = num;
setPrevious(prev);
setNext(next);
}
public void setDigit(int num) {
digit = num;
}
public void setPrevious(Node previousNode) {
previous = previousNode;
}
public void setNext(Node nextNode) {
next = nextNode;
}
public int getDigit() {
return digit;
}
public Node getPrevious() {
return previous;
}
public Node getNext() {
return next;
}
}
Code:
public class DoublyLinkedList {
private Node head = new Node();
private Node tail = new Node();
private int length = 0;
public DoublyLinkedList() {
head.setPrevious(null);
head.setNext(tail);
tail.setPrevious(head);
tail.setNext(null);
}
.
.
.
public void insertHead(int num) {
Node current = head;
Node temp = new Node(num, null, current);
current.setPrevious(temp);
head = temp;
length++;
}
public void insertTail(int num) {
Node current = tail;
Node temp = new Node(num, current, null);
current.setNext(temp);
tail = temp;
length++;
}
}
For example, I have a linked list like so:
1-->2-->3-->4-->5
I want to add '99' at the end so I call this statement:
list.insertTail(99);
Instead of putting the '99' at the end, it would always put a '0' instead.
1-->2-->3-->4-->5-->0
When I try to insert a head node, it does it properly, so I don't know why it's acting up for the tail node.
Re: Adding tail node to a doubly linked list
Have you tried debugging your code by adding printlns to show the logic flow and the values of variables as they change?
There is no way for anyone to test your code segments.
Re: Adding tail node to a doubly linked list
Yeah, I tried doing that, but I haven't been able to figure it out yet. I'm mainly concerned if my insertTail() method looks logically correct.
Re: Adding tail node to a doubly linked list
That is the way I solve most logic problems like this. Print out the data to see what is happening.
For example have you found out where the node with the 99 has gone and where the node with 0 comes from?
Can you write the steps the program should take to chain in a node at the tail in pseudo code?
And document what each of the steps in the insertTail method does.
For debugging, add a toString to the Node class that will return the three fields in the node.
Re: Adding tail node to a doubly linked list
Ok, I figured it out. I didn't realize that for a doubly linked list, both head and tail nodes are suppose to be null. Because of that, I was programming the insert head/tail methods wrong all this time. Thanks for the help.