使用Java创建镜像链表

时间:2010-04-15 05:04:50

标签: java linked-list data-structures

Linked-List:镜像

考虑单个链接的整数列表的节点的以下私有类:

private class Node{
public int value;
public Node next;
}

一个名为ListImpl的包装类包含一个指针,称为start的第一个节点 节点的链接列表。

使用签名:

为ListImpl编写实例方法
public void mirror();

这会使start指向的链表的反转副本并附加该副本 到列表的末尾。所以,例如列表:

开始1 2 3

调用镜像后,

变为:

开始1 2 3 3 2 1

注意:在你的回答中,你不需要为ListImpl定义其余的类 镜子方法。

4 个答案:

答案 0 :(得分:2)

public void mirror() {
    if (start != null) {
        Node prev = null;
        Node p = start;
        Node q = null;
        while (p != null) {
            Node n = new Node();
            n.value = p.value;
            n.next = q;
            q = n;
            prev = p;
            p = p.next;
        }
        prev.next = q;
    }
}

答案 1 :(得分:1)

你的问题是什么?这看起来像是一个运动问题。您在寻找优化的解决方案吗?一种方法是迭代列表并将元素添加到堆栈,最后在迭代后将它们添加为节点。

答案 2 :(得分:1)

由于Maurice提供了looping solution,我将提供一个递归解决方案。

void mirror()
{
    if (start == null) return;
    mirrorSublist(start);
}

// returns the last node of the mirrored sublist
Node mirrorSublist(Node firstOfSublist)
{
    Node lastOfSublist = new Node();
    lastOfSublist.value = firstOfSublist.value;
    lastOfSublist.next = null;
    if (firstOfSublist.next == null)
    {
        firstOfSublist.next = lastOfSublist;
    }
    else
    {
        Node secondToLastOfSublist = mirrorSublist(firstOfSublist.next);
        secondToLastOfSublist.next = lastOfSublist;
    }
    return lastOfSublist;
}

答案 3 :(得分:0)

您可以使用这种方法:

Algorithm findLinkedListMirror
  If list does not exist 
    return

  Let start and end be pointers to type Node
  Position start to the first node of the list
  Position end to last node of the list

  While(start != end.next)
    Add a new node next to end with value start.data
    start = start.next
  End While

End