递归 - 具有void函数返回类型的反向链接列表

时间:2013-07-08 11:44:15

标签: java algorithm data-structures recursion linked-list

我试图使用递归来反转链表。我得到了解决方案,但无法让它在互联网上找到以下问题。

  

使用递归反转链表但函数应该为void   返回类型。

我能够将返回类型的函数实现为 Node 。以下是我的解决方案。

public static Node recursive(Node start) {

    // exit condition
    if(start == null || start.next == null)
        return start;

    Node remainingNode = recursive(start.next);

    Node current = remainingNode;

    while(current.next != null)
           current = current.next;

    current.next = start;
    start.next = null;
    return remainingNode;
 }

我无法想象是否会有这样的解决方案来解决这个问题。

有什么建议吗?

10 个答案:

答案 0 :(得分:3)

经过测试,它可以正常工作(假设您拥有自己的链接列表实现,其中Node知道next节点。)

public static void reverse(Node previous, Node current) {
    //if there is next node...
    if (current.next != null) {
        //...go forth and pwn
        reverse(current, current.next);
    }

    if (previous == null) {
        // this was the start node
        current.next= null;
    } else {
        //reverse
        current.next= previous;
    }   
}

你用

来调用它
reverse(null, startNode);

答案 1 :(得分:1)

public void recursiveDisplay(Link current){

        if(current== null)
           return ;
        recursiveDisplay(current.next);
        current.display();
}

答案 2 :(得分:1)

static StringBuilder reverseStr = new StringBuilder();

public static void main(String args[]) {
    String str = "9876543210";
    reverse(str, str.length() - 1);
}

public static void reverse(String str, int index) {
    if (index < 0) {
        System.out.println(reverseStr.toString());
    } else {
        reverseStr.append(str.charAt(index));
        reverse(str, index - 1);
        index--;
    }
}

答案 3 :(得分:0)

这应该有效

static void reverse(List list, int p) {
    if (p == list.size() / 2) {
        return;
    }
    Object o1 = list.get(p);
    Object o2 = list.get(list.size() - p - 1);
    list.set(p, o2);
    list.set(list.size() - p - 1, o1);
    reverse(list, p + 1);
}

虽然要使用LinkedList高效,但应该重构为使用ListIterator

答案 4 :(得分:0)

我不熟悉Java,但这是一个C ++版本。在反转列表后,列表的头部仍然保留,这意味着仍然可以从旧列表头List* h访问列表。

void reverse(List* h) {
    if (!h || !h->next) {
      return;
    }
    if (!h->next->next) {
      swap(h->value, h->next->value);
      return;
    }
    auto next_of_next = h->next->next;
    auto new_head = h->next;
    reverse(h->next);
    swap(h->value, new_head->value);
    next_of_next->next = new_head;
    h->next = new_head->next;
    new_head->next = nullptr;
  }

答案 5 :(得分:0)

请尝试使用此代码 - 它实际上可以正常工作

    public static ListElement reverseListConstantStorage(ListElement head) {
    return reverse(null,head);
}

private static ListElement reverse(ListElement previous, ListElement current) {

    ListElement newHead = null;
    if (current.getNext() != null) {
        newHead = reverse(current, current.getNext());
    } else {//end of the list
        newHead=current;
        newHead.setNext(previous);
    }

    current.setNext(previous);        
    return newHead;        
}

答案 6 :(得分:0)

public static Node recurse2(Node node){
    Node head =null;
    if(node.next == null) return node;
    Node previous=node, current = node.next;
    head = recurse2(node.next);
    current.next = previous;
    previous.next = null;
    return head;

}

调用函数时,返回如下的返回值:

 list.head=recurse2(list.head);

答案 7 :(得分:0)

以下功能基于darijan的选择答案,我所做的就是添加2行代码,以便它适合您想要工作的代码:

public void reverse(Node previous, Node current) {
        //if there is next node...
        if (current.next != null) {
            //...go forth and pwn
            reverse(current, current.next);
        }
        else this.head = current;/*end of the list <-- This line alone would be the fix
        since you will now have the former tail of the Linked List set as the new head*/


        if (previous == null) {
            // this was the start node
            current.next= null;
            this.tail = current; /*No need for that one if you're not using a Node in 
            your class to represent the last Node in the given list*/
        } else {
            //reverse
            current.next= previous;
        }   
    }

另外,我已将其更改为非静态函数,因此使用它的方式为:myLinkedList.reverse(null, myLinkedList.head);

答案 8 :(得分:0)

这是我的版本 - void ReverseWithRecursion(Node currentNode)                     - 它是LinkListDemo类的方法,因此可以访问头

  1. 基础案例 - 如果Node为null,则不执行任何操作并返回。            如果Node-&gt; Next为null,则“Make it head”并返回。
  2. 其他案例 - 反转currentNode的下一个。

    public void ReverseWithRecursion(Node currentNode){
       if(currentNode == null) return;
       if(currentNode.next == null) {head = currentNode; return;}
    
       Node first = currentNode;
       Node rest = currentNode.next;
    
       RevereseWithRecursion(rest);
    
       first.next.next = first;
       first.next = null;
    }
    
  3. 你这样称呼它 -

    LinkListDemo ll = new LinkListDemo(); // assueme class is available
    ll.insert(1);  // Assume method is available
    ll.insert(2);
    ll.insert(3);
    ll.ReverseWithRecursion(ll.head);
    

答案 9 :(得分:-1)

我能想到的最简单的方法是:

public static <T> void reverse( LinkedList<T> list )
{
    if (list.size() <= 1) {
        return;
    }
    T first = list.removeFirst();
    reverse( list);
    list.addLast( first );
}