反转链接列表不解析firstNode

时间:2014-02-19 06:01:59

标签: java linked-list

我写了一个Linked List实现,它以firstNode为首,以lastNode结束。我正在尝试颠倒它除了firstNode之外完美无缺的列表。假设我从firstNode开始到lastNode的列表中有以下数据:“one”,“two”,“three”,“four”,“five”。当我运行reverseMePlz()方法时,将显示以下内容:四个,三个,两个,一个。原始的firstNode(一个)现在是lastNode,而原始的lastNode(五个)不是第一个节点,而是两个应该是第二个节点成为firstNode,所以基本上它正在删除最初应该是firstNode的lastNode。这是我的编码:

public void reverseMePlz()
{
    Node nextNode = null;

    Node currentNode = firstNode;

    while (currentNode.next != null)
    {
        nextNode = currentNode.next;
        currentNode.next = currentNode.previous;

        firstNode = currentNode;
        currentNode = nextNode;

    }

    lastNode = currentNode;

}

2 个答案:

答案 0 :(得分:0)

while循环的条件更改为

while(currentNode!=null)

这是代码,

public void reverse(Node headNode) {
        Node nextNode = null;
        Node previousNode = null;
        Node currentNode = headNode;

        while(currentNode!=null) {
            nextNode = currentNode.next;
            currentNode.next = previousNode;
            currentNode.previous = nextNode;
            previousNode = currentNode;
            currentNode = nextNode;
        }
        headNode = previousNode;
}

答案 1 :(得分:0)

我明白了。这是我的解决方案:

public void reverseMePlz()
    {
        Node nextNode = null, currentNode = firstNode, first = firstNode;

        while (currentNode.next != null)
        {
            nextNode = currentNode.next;

            currentNode.next = currentNode.previous;
            currentNode.previous = nextNode;

            firstNode = currentNode;
            currentNode = nextNode;

        }

        lastNode.next = firstNode;
        firstNode = lastNode;
        lastNode = first;
        firstNode.previous = null;

    }