我正在尝试在Java中定义自己的双向链表类。我当前的方法将整数添加到LinkedList(按从最低值到最高值的顺序),从最低到最高打印它们,并从最高到最低打印它们。我从高到低打印的方法必须通过使用当前节点指向前一节点的指针来知道下一个要打印的数字。但是,由于某种原因,我的add方法没有正确地分配我以前的节点指针。 LinkedList类看起来像
public class DoubleLink {
/**
* Class to create a node object for double linked list
* @author Nick Gilbert
*/
private class Node {
int num;
Node next;
Node previous;
public Node(int num, Node next, Node previous) {
this.num = num;
this.next = next;
this.previous = previous;
}
}
private Node head;
public DoubleLink() { //All lists start out empty
head = null;
}
public void add(int num) {
if(head == null) //If num is first entry to list
{
head = new Node(num, null, null);
return;
}
Node current = null; //Pointer to iterate through list
for(current = head; current.next != null; current = current.next){ //Starting at head and going to end
if(current.next.num >= num) { //if next number is greater than number we want to add then we've found the spot to add it to
current.next = new Node(num, current.next, current);
if(num < head.num) //If this statement is true then the num we added is less than the current head's num which means the head needs to be reassigned
{
int temp = current.next.num;
current.next.num = head.num;
head.num = temp;
}
return;
}
}
current.next = new Node(num, null, current);
}
public void print() { //prints from lowest number to highest
for(Node current = head; current != null; current = current.next) {
System.out.println(current.num );
}
}
public void printBackwards() { //prints from highest to lowest
Node current = null;
for(current = head; current != null; current = current.next) {
if(current.next == null)
break;
}
Node tail = new Node(current.num, null, current.previous);
for(current = tail; current != null; current = current.previous) {
System.out.println(current.num );
}
}
}
并且下一个代码段包含我的测试用例
public class DoubleLinkTester {
public static void main(String[] args) {
DoubleLink list = new DoubleLink();
list.add(5);
list.add(9);
list.add(7);
list.add(3);
list.add(8);
list.add(10);
list.add(4);
list.add(6);
System.out.println("Call print, should get 3,4,5,6,7,8,9,10");
list.print();
System.out.println("Call printBackwards, should get 10,9,8,7,6,5,4,3");
list.printBackwards();
使用上面的测试用例执行printBackwards方法打印10,9,3而不是预期的10,9,8,7,6,5,4,3。我相信这是因为add方法没有正确地重新分配添加了以前数字的指针作为新的数字,但我不知道如何解决它。
答案 0 :(得分:3)
您错过了将下一个节点的上一个节点重置为添加的新节点。
public void add(int num) {
// Code above this remains same
if(current.next.num >= num) { //if next number is greater than number we want to add then we've found the spot to add it to
Node actualNext = current.next; // Missed
current.next = new Node(num, current.next, current);
actualNext.previous = current.next; //Missed
// Code below this remains same
}