1. Member
Join Date
Sep 2011
Posts
4
Rep Power
0

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.

Java 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;
}

}```

Java Code:
```public class DoublyLinkedList {
private Node head = new Node();
private Node tail = new Node();
private int length = 0;

tail.setNext(null);
}

.
.
.

Node temp = new Node(num, null, current);
current.setPrevious(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.

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.

3. Member
Join Date
Sep 2011
Posts
4
Rep Power
0

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.

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.
Last edited by Norm; 09-21-2011 at 09:58 PM.

5. Member
Join Date
Sep 2011
Posts
4
Rep Power
0

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.

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•