反向单链表-代码改进



我正在努力提高我的递归技能(或者可能是第一次获得它们:))。为此,我编写了一个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;
    }
}

这段代码工作得很好,但是为了学习,我想避免使用全局变量(节点prev)来进行递归函数内部的操作。那么这个函数可以重写以完全避免它吗?欢迎任何其他优化:)

一个更好的实现应该如下:

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;
}
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;
}

相关内容

  • 没有找到相关文章

最新更新