反向单链表 - 代码改进

时间:2013-06-18 14:36:08

标签: java recursion linked-list

我正在努力提高我的递归技能(或者可能是第一次获得它们:))。为此,我写了一个Java代码来反转单链表,如下所示:

node head, prev; // head is pointing to the start of the linked list

void reverselist(node current) {
    if (current.next != null) {
        reverselist(current.next);
    }
    if (current.next == null) {
        this.head = current;
        prev = current;
    }
    else {
        prev.next = current;
        current.next = null;
        prev = current;
    }
}

这段代码工作正常,但为了学习,我想避免在递归函数中使用全局变量(node prev)进行操作。那么可以重写这个函数来完全避免它吗?欢迎任何其他优化:)

2 个答案:

答案 0 :(得分:2)

更好的实施应如下:

public Node reverse(Node current)
{
 if (current== null || current.next==null) return current;
 Node nextItem = current.next;
 current.next = null;
 Node reverseRest = reverse(nextItem);
 nextItem.next = current;
 return reverseRest;
}

答案 1 :(得分:0)

public Linkedlist reverseList (LinkedList list) {

    Node temp = null;
    Node nextNode = list;
    while(list != null) {
        nextNode = list.next;
        list.next = temp;
        temp = list;
        list = nextNode;
    }
    return temp;
}

private class LinkedList {

    int data;
    LinkedList next;
}