我在实现两个双向链表的连接时遇到了麻烦。这是我的concat方法。看起来没问题,但结果我得到第一个列表的尾部元素,以及第二个列表的所有元素。
public Node<?> concat(Node<?> head1, Node<?> head2)
{
if(head1 == null)
{
return head2;
}
if(head2 == null)
{
return head1;
}
Node<?> n = head1;
while(n.getNext() != null)
{
n = n.getNext();
}
n.setNext(head2);
return head1;
}
编辑:DoubleLinkedList类:
public class DoubleLinkedList<E>
{
protected int size;
protected Node<?> head, tail;
public DoubleLinkedList()
{
size = 0;
clear();
}
public void clear()
{
head = null;
tail = null;
}
public int size()
{
return size;
}
public boolean isEmpty()
{
return head == null;
}
public Node<?> getHead()
{
return head;
}
public Node<?> getTail()
{
return tail;
}
public void add(E value)
{
Node<E> node = new Node<E>(value);
if(isEmpty())
{
head = node;
tail = node;
}
else
{
tail.setNext(node);
node.setPrevious(tail);
tail = node;
}
size++;
}
public int indexOf(E value)
{
Node<?> find = head;
for(int i=0;i<size;i++)
{
E n = (E}find.getValue();
if(n.equals(value))
{
return i;
}
find = find.getNext();
}
return -1;
}
public Node<?> concat(Node<?> head1, Node<?> head2)
{
if(head1 == null)
{
return head2;
}
if(head2 == null)
{
return head1;
}
Node<?> n = head1;
while(n.getNext() != null)
{
n = n.getNext();
}
n.setNext(head2);
head2.setPrevious(n);
return n;
}
private static final class Node<E>
{
private E value;
private Node<?> next, previous;
public Node(E value)
{
this(value, null, null);
}
public Node(E value, Node<?> n, Node<?> p)
{
this.value = value;
this.next = n;
this.previous = p;
}
public E getValue()
{
return value;
}
public void setNext(Node<?> n)
{
this.next = n;
}
public Node<?> getNext()
{
return next;
}
public void setPrevious(Node<?> p)
{
this.previous = p;
}
public Node<?> getPrevious()
{
return previous;
}
}
}
答案 0 :(得分:0)
而不是返回head1
,请尝试返回n
。