【问题标题】:Two doubly linked lists concatenation JAVA两个双向链表串联JAVA
【发布时间】:2015-03-17 19:12:05
【问题描述】:

我在实现两个双向链表的连接时遇到了麻烦。这是我的 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;
    }
}

}

【问题讨论】:

  • 如果它看起来不错有什么问题?
  • 如果没有看到你的 doublyLinkedList 的实现,就很难看出问题所在
  • 既然是双向链接的,还需要设置head2的previous
  • @Andremoniy 似乎并不意味着没问题。在我看来,这似乎没问题,但也许我错了,我正在寻求帮助找出错误所在:)
  • 如果你有getTail(),不要使用getNext() 迭代到最后。

标签: java concatenation


【解决方案1】:

不要返回head1,而是尝试返回n

【讨论】:

  • 不幸的是它没有帮助:/
  • 看来while(n.getNext() != null) { n = n.getNext(); } n.setNext(head2); return n; 是对的。仔细检查您的节点类。 getNext()setNext() 做对了吗?
  • 它也没有帮助,但是我以不同的方式编写了这个方法并且它有效。感谢您的尝试:)
猜你喜欢
  • 1970-01-01
  • 2021-07-05
  • 2015-08-05
  • 1970-01-01
  • 1970-01-01
  • 2021-01-17
  • 2015-07-14
  • 2015-03-14
  • 1970-01-01
相关资源
最近更新 更多