递归地反转Java中的链表


101

我已经在一个类的Java项目上工作了一段时间。它是链表(此处称为AddressList,包含称为的简单节点ListNode)的实现。问题在于,一切都必须使用递归算法来完成。我可以用一种方法来做所有的事情:public AddressList reverse()

ListNode:

public class ListNode{
  public String data;
  public ListNode next;
}

现在,我的reverse函数只是调用一个带有参数以允许递归的辅助函数。

public AddressList reverse(){
  return new AddressList(this.reverse(this.head));
}

我的助手功能具有的签名private ListNode reverse(ListNode current)

目前,我让它使用堆栈来迭代地工作,但这不是规范所要求的。我在C语言中找到了一种算法,该算法可以递归地将其递归逆转并将其转换为Java代码,并且可以正常工作,但是我对此并不了解。

编辑:没关系,我在此期间已找到答案。

private AddressList reverse(ListNode current, AddressList reversedList){
  if(current == null) 
      return reversedList;
  reversedList.addToFront(current.getData());
  return this.reverse(current.getNext(), reversedList);
}

当我在这里时,有人看到此路线有任何问题吗?


2
不,您的解决方案没有问题。相反,它甚至比受欢迎的“ Little Lisper”解决方案“更好”,因为它可以使原始列表保持完整。这在多核设置中特别有价值,在这种情况下,强烈建议使用不可变值。
Ingo

Answers:


318

在一个答复中有代码将其说明清楚,但是您可能会发现,通过问和回答一些微小的问题(这是《小丽人》中的方法),更容易从头开始。

  1. null(空列表)的反向是什么?空值。
  2. 一个元素列表的反向作用是什么?元素。
  3. n元素列表的反向操作是什么?列表其余部分的倒序,后跟第一个元素。

public ListNode Reverse(ListNode list)
{
    if (list == null) return null; // first question

    if (list.next == null) return list; // second question

    // third question - in Lisp this is easy, but we don't have cons
    // so we grab the second element (which will be the last after we reverse it)

    ListNode secondElem = list.next;

    // bug fix - need to unlink list from the rest or you will get a cycle
    list.next = null;

    // then we reverse everything from the second element on
    ListNode reverseRest = Reverse(secondElem);

    // then we join the two lists
    secondElem.next = list;

    return reverseRest;
}

30
哇,我喜欢整个“三个问题”。
sdellysse

4
谢谢。这个小问题应该是学习Lisp的基础。这也是从newbs中隐藏归纳法的一种方式,本质上就是这种模式。如果您确实想解决此类问题,我建议您阅读《小丽人》。
底座

44
特殊情况下的例外。为什么要对可通过if测试的已知条件使用捕获?
路加·谢弗

4
我相信您不需要创建变量:secondElem,因为list.next仍然是secondElem。在“ ListNode reverseRest = Reverse(secondElem);”之后,您可以首先执行“ list.next.next = list”,然后执行“ list.next = null”。就是这样。
ChuanRocks

3
您能解释为什么list.next = null吗?我试图了解周期,但没有得到。
罗希特2013年

29

面试时有人问我这个问题,但由于有点紧张,我很生气。

这应该反转一个单向链表,并用reverse(head,NULL)调用;因此,如果这是您的列表:

1-> 2-> 3-> 4-> 5->空
它会变成:
5-> 4-> 3-> 2-> 1->空

    //Takes as parameters a node in a linked list, and p, the previous node in that list
    //returns the head of the new list
    Node reverse(Node n,Node p){   
        if(n==null) return null;
        if(n.next==null){ //if this is the end of the list, then this is the new head
            n.next=p;
            return n;
        }
        Node r=reverse(n.next,n);  //call reverse for the next node, 
                                      //using yourself as the previous node
        n.next=p;                     //Set your next node to be the previous node 
        return r;                     //Return the head of the new list
    }
    

编辑:香港专业教育学院完成了6像这样的编辑,表明它对我来说仍然有些棘手


2
老实说,如果指定了Java,我会对采访中的“必须递归”的要求感到有些沮丧。否则我将使用p = null; while(n.next!= null){n2 = n.next; n.next = p; p = n; n = n2;} n.next = p; 返回n;。O(N)堆用于鸟类。
史蒂夫·杰索普

哦,是的,在头上也有一个空检查,这就是Java。
史蒂夫·杰索普

23

我走了一半(直到为空,直到plinth建议一个节点为止),但是在进行递归调用后迷路了。但是,在阅读了plinth的文章之后,我想到了以下内容:

Node reverse(Node head) {
  // if head is null or only one node, it's reverse of itself.
  if ( (head==null) || (head.next == null) ) return head;

  // reverse the sub-list leaving the head node.
  Node reverse = reverse(head.next);

  // head.next still points to the last element of reversed sub-list.
  // so move the head to end.
  head.next.next = head;

  // point last node to nil, (get rid of cycles)
  head.next = null;
  return reverse;
}

非常好。就像做坏事一样:)
Karthikeyan D

9

这是另一个递归解决方案。与其他函数相比,它在递归函数中的代码更少,因此它可能会更快一些。这是C#,但我相信Java会非常相似。

class Node<T>
{
    Node<T> next;
    public T data;
}

class LinkedList<T>
{
    Node<T> head = null;

    public void Reverse()
    {
        if (head != null)
            head = RecursiveReverse(null, head);
    }

    private Node<T> RecursiveReverse(Node<T> prev, Node<T> curr)
    {
        Node<T> next = curr.next;
        curr.next = prev;
        return (next == null) ? curr : RecursiveReverse(curr, next);
    }
}

8

该算法将需要采用以下模型,

  • 追踪头部
  • 递归直到链接列表的结尾
  • 反向联动

结构体:

Head    
|    
1-->2-->3-->4-->N-->null

null-->1-->2-->3-->4-->N<--null

null-->1-->2-->3-->4<--N<--null

null-->1-->2-->3<--4<--N<--null

null-->1-->2<--3<--4<--N<--null

null-->1<--2<--3<--4<--N<--null

null<--1<--2<--3<--4<--N
                       |
                       Head

码:

public ListNode reverse(ListNode toBeNextNode, ListNode currentNode)
{               
        ListNode currentHead = currentNode; // keep track of the head

        if ((currentNode==null ||currentNode.next==null )&& toBeNextNode ==null)return currentHead; // ignore for size 0 & 1

        if (currentNode.next!=null)currentHead = reverse(currentNode, currentNode.next); // travarse till end recursively

        currentNode.next = toBeNextNode; // reverse link

        return currentHead;
}

输出:

head-->12345

head-->54321

7

我认为这是更清洁的解决方案,类似于LISP

// Example:
// reverse0(1->2->3, null) => 
//      reverse0(2->3, 1) => 
//          reverse0(3, 2->1) => reverse0(null, 3->2->1)
// once the first argument is null, return the second arg
// which is nothing but the reveresed list.

Link reverse0(Link f, Link n) {
    if (f != null) {
        Link t = new Link(f.data1, f.data2); 
        t.nextLink = n;                      
        f = f.nextLink;             // assuming first had n elements before, 
                                    // now it has (n-1) elements
        reverse0(f, t);
    }
    return n;
}

7

我知道这是一个老帖子,但是大多数答案不是尾递归,即它们在从递归调用返回后进行一些操作,因此不是最有效的。

这是尾部递归版本:

public Node reverse(Node previous, Node current) {
    if(previous == null)
        return null;
    if(previous.equals(head))
        previous.setNext(null);
    if(current == null) {    // end of list
        head = previous;
        return head;
    } else {
                    Node temp = current.getNext();
        current.setNext(previous);
        reverse(current, temp);
    }
    return null;    //should never reach here.
} 

致电:

Node newHead = reverse(head, head.getNext());

9
您在方法中引用了一个名为“ head”的变量,但未在任何地方声明该变量。
马拉松赛

它可能是包含Node head属性的List类的方法
ChrisMcJava 2014年

4
void reverse(node1,node2){
if(node1.next!= null)
      反向(node1.next,node1);
   node1.next = node2;
}
将此方法称为reverse(start,null);

4
public Node reverseListRecursive(Node curr)
{
    if(curr == null){//Base case
        return head;
    }
    else{
        (reverseListRecursive(curr.next)).next = (curr);
    }
    return curr;
}

3
public void reverse() {
    head = reverseNodes(null, head);
}

private Node reverseNodes(Node prevNode, Node currentNode) {
    if (currentNode == null)
        return prevNode;
    Node nextNode = currentNode.next;
    currentNode.next = prevNode;
    return reverseNodes(currentNode, nextNode);
}

我认为这是最好的解决方案...简单,可优化的尾部递归并且只有一个null检查。
sdanzig,2015年

2
public static ListNode recRev(ListNode curr){

    if(curr.next == null){
        return curr;
    }
    ListNode head = recRev(curr.next);
    curr.next.next = curr;
    curr.next = null;

    // propogate the head value
    return head;

}

这是最好的解决方案,但不是最好的答案,因为没有给出任何解释:)。首先,我得出了类似的解决方案,但没有参考。该解决方案解决了该问题。
OpenUserX03 2014年

2

通过递归算法进行反转。

public ListNode reverse(ListNode head) {
    if (head == null || head.next == null) return head;    
    ListNode rHead = reverse(head.next);
    rHead.next = head;
    head = null;
    return rHead;
}

通过迭代

public ListNode reverse(ListNode head) {
    if (head == null || head.next == null) return head;    
    ListNode prev = null;
    ListNode cur = head
    ListNode next = head.next;
    while (next != null) {
        cur.next = prev;
        prev = cur;
        cur = next;
        next = next.next;
    }
    return cur;
}

不幸的是,您的递归反向是错误的!
Sree Aurovindh

@SreeAurovindh-为什么?
rayryeng 2014年

2

该解决方案表明不需要参数。

/**
 * Reverse the list
 * @return reference to the new list head
 */
public LinkNode reverse() {
    if (next == null) {
        return this; // Return the old tail of the list as the new head
    }
    LinkNode oldTail = next.reverse(); // Recurse to find the old tail
    next.next = this; // The old next node now points back to this node
    next = null; // Make sure old head has no next
    return oldTail; // Return the old tail all the way back to the top
}

以下是支持代码,以证明其有效:

public class LinkNode {
    private char name;
    private LinkNode next;

    /**
     * Return a linked list of nodes, whose names are characters from the given string
     * @param str node names
     */
    public LinkNode(String str) {
        if ((str == null) || (str.length() == 0)) {
            throw new IllegalArgumentException("LinkNode constructor arg: " + str);
        }
        name = str.charAt(0);
        if (str.length() > 1) {
            next = new LinkNode(str.substring(1));
        }
    }

    public String toString() {
        return name + ((next == null) ? "" : next.toString());
    }

    public static void main(String[] args) {
        LinkNode head = new LinkNode("abc");
        System.out.println(head);
        System.out.println(head.reverse());
    }
}

2

这是一个简单的迭代方法:

public static Node reverse(Node root) {
    if (root == null || root.next == null) {
        return root;
    }

    Node curr, prev, next;
    curr = root; prev = next = null;
    while (curr != null) {
        next = curr.next;
        curr.next = prev;

        prev = curr;
        curr = next;
    }
    return prev;
}

这是一种递归方法:

public static Node reverseR(Node node) {
    if (node == null || node.next == null) {
        return node;
    }

    Node next = node.next;
    node.next = null;

    Node remaining = reverseR(next);
    next.next = node;
    return remaining;
}

1

由于Java总是按值传递,因此要递归地反转Java中的链表,请确保在递归结束时返回“新头”(还原后的头节点)。

static ListNode reverseR(ListNode head) {
    if (head == null || head.next == null) {
        return head;
    }

    ListNode first = head;
    ListNode rest = head.next;

    // reverse the rest of the list recursively
    head = reverseR(rest);

    // fix the first node after recursion
    first.next.next = first;
    first.next = null;

    return head;
}

1

PointZeroTwo在Java中得到了很好的答案和相同的答案...

public void reverseList(){
    if(head!=null){
        head = reverseListNodes(null , head);
    }
}

private Node reverseListNodes(Node parent , Node child ){
    Node next = child.next;
    child.next = parent;
    return (next==null)?child:reverseListNodes(child, next);
}

这是完美的,因为您并不总是希望该list方法将list作为参数,而是希望自己使用自己的孩子来反转自己,谢谢
Manu

0
public class Singlelinkedlist {
  public static void main(String[] args) {
    Elem list  = new Elem();
    Reverse(list); //list is populate some  where or some how
  }

  //this  is the part you should be concerned with the function/Method has only 3 lines

  public static void Reverse(Elem e){
    if (e!=null)
      if(e.next !=null )
        Reverse(e.next);
    //System.out.println(e.data);
  }
}

class Elem {
  public Elem next;    // Link to next element in the list.
  public String data;  // Reference to the data.
}

0
public Node reverseRec(Node prev, Node curr) {
    if (curr == null) return null;  

    if (curr.next == null) {
        curr.next = prev;
        return curr;

    } else {
        Node temp = curr.next; 
        curr.next = prev;
        return reverseRec(curr, temp);
    }               
}

调用使用:head = reverseRec(null,head);


0

其他人所做的,在其他帖子中是内容的游戏,我所做的是链接列表的游戏,它使LinkedList的成员反向,而不是成员的Value反向。

Public LinkedList reverse(LinkedList List)
{
       if(List == null)
               return null;
       if(List.next() == null)
              return List;
       LinkedList temp = this.reverse( List.next() );
       return temp.setNext( List );
}

抱歉,您还需要一个辅助方法来设置尾巴的下一个,值为空
Nima Ghaedsharafi

0
package com.mypackage;
class list{

    node first;    
    node last;

    list(){
    first=null;
    last=null;
}

/*returns true if first is null*/
public boolean isEmpty(){
    return first==null;
}
/*Method for insertion*/

public void insert(int value){

    if(isEmpty()){
        first=last=new node(value);
        last.next=null;
    }
    else{
        node temp=new node(value);
        last.next=temp;
        last=temp;
        last.next=null;
    }

}
/*simple traversal from beginning*/
public void traverse(){
    node t=first;
    while(!isEmpty() && t!=null){
        t.printval();
        t= t.next;
    }
}
/*static method for creating a reversed linked list*/
public static void reverse(node n,list l1){

    if(n.next!=null)
        reverse(n.next,l1);/*will traverse to the very end*/
    l1.insert(n.value);/*every stack frame will do insertion now*/

}
/*private inner class node*/
private class node{
    int value;
    node next;
    node(int value){
        this.value=value;
    }
    void printval(){
        System.out.print(value+" ");
    }
}

 }

0

解决方案是:

package basic;

import custom.ds.nodes.Node;

public class RevLinkedList {

private static Node<Integer> first = null;

public static void main(String[] args) {
    Node<Integer> f = new Node<Integer>();
    Node<Integer> s = new Node<Integer>();
    Node<Integer> t = new Node<Integer>();
    Node<Integer> fo = new Node<Integer>();
    f.setNext(s);
    s.setNext(t);
    t.setNext(fo);
    fo.setNext(null);

    f.setItem(1);
    s.setItem(2);
    t.setItem(3);
    fo.setItem(4);
    Node<Integer> curr = f;
    display(curr);
    revLL(null, f);
    display(first);
}

public static void display(Node<Integer> curr) {
    while (curr.getNext() != null) {
        System.out.println(curr.getItem());
        System.out.println(curr.getNext());
        curr = curr.getNext();
    }
}

public static void revLL(Node<Integer> pn, Node<Integer> cn) {
    while (cn.getNext() != null) {
        revLL(cn, cn.getNext());
        break;
    }
    if (cn.getNext() == null) {
        first = cn;
    }
    cn.setNext(pn);
}

}


0
static void reverseList(){

if(head!=null||head.next!=null){
ListNode tail=head;//head points to tail


ListNode Second=head.next;
ListNode Third=Second.next;
tail.next=null;//tail previous head is poiniting null
Second.next=tail;
ListNode current=Third;
ListNode prev=Second;
if(Third.next!=null){



    while(current!=null){
    ListNode    next=current.next;
        current.next=prev;
        prev=current;
        current=next;
    }
    }
head=prev;//new head
}
}
class ListNode{
    public int data;
    public ListNode next;
    public int getData() {
        return data;
    }

    public ListNode(int data) {
        super();
        this.data = data;
        this.next=null;
    }

    public ListNode(int data, ListNode next) {
        super();
        this.data = data;
        this.next = next;
    }

    public void setData(int data) {
        this.data = data;
    }
    public ListNode getNext() {
        return next;
    }
    public void setNext(ListNode next) {
        this.next = next;
    }





}

0
private Node ReverseList(Node current, Node previous)
    {
        if (current == null) return null;
        Node originalNext = current.next;
        current.next = previous;
        if (originalNext == null) return current;
        return ReverseList(originalNext, current);
    }

从ReverseList(head,null)开始

0
//this function reverses the linked list
public Node reverseList(Node p) {
    if(head == null){
        return null;
    }
    //make the last node as head
    if(p.next == null){
        head.next = null;
        head = p;
        return p;
    }
    //traverse to the last node, then reverse the pointers by assigning the 2nd last node to last node and so on..
    return reverseList(p.next).next = p;
}

0
//Recursive solution
class SLL
{
   int data;
   SLL next;
}

SLL reverse(SLL head)
{
  //base case - 0 or 1 elements
  if(head == null || head.next == null) return head;

  SLL temp = reverse(head.next);
  head.next.next = head;
  head.next = null;
  return temp;
}

0

一篇讨论递归数据结构的不变实现的文章的启发,我使用Swift将另一种解决方案放在一起。

领先的答案文档解决方案通过突出以下主题:

  1. nil(空列表)的反向作用是什么?
    • 这里没关系,因为我们在Swift中有nil保护。
  2. 一个元素列表的反向作用是什么?
    • 元素本身
  3. n元素列表的反向操作是什么?
    • 第二个元素的反序,后跟第一个元素。

在下面的解决方案中,我已经在适当的地方列出了这些信息。

/**
 Node is a class that stores an arbitrary value of generic type T 
 and a pointer to another Node of the same time.  This is a recursive 
 data structure representative of a member of a unidirectional linked
 list.
 */
public class Node<T> {
    public let value: T
    public let next: Node<T>?

    public init(value: T, next: Node<T>?) {
        self.value = value
        self.next = next
    }

    public func reversedList() -> Node<T> {
        if let next = self.next {
            // 3. The reverse of the second element on followed by the first element.
            return next.reversedList() + value
        } else {
            // 2. Reverse of a one element list is itself
            return self
        }
    }
}

/**
 @return Returns a newly created Node consisting of the lhs list appended with rhs value.
 */
public func +<T>(lhs: Node<T>, rhs: T) -> Node<T> {
    let tail: Node<T>?
    if let next = lhs.next {
        // The new tail is created recursively, as long as there is a next node.
        tail = next + rhs
    } else {
        // If there is not a next node, create a new tail node to append
        tail = Node<T>(value: rhs, next: nil)
    }
    // Return a newly created Node consisting of the lhs list appended with rhs value.
    return Node<T>(value: lhs.value, next: tail)
}

0

使用递归反转链表。这个想法是通过反转链接来调整链接。

  public ListNode reverseR(ListNode p) {

       //Base condition, Once you reach the last node,return p                                           
        if (p == null || p.next == null) { 
            return p;
        }
       //Go on making the recursive call till reach the last node,now head points to the last node

        ListNode head  = reverseR(p.next);  //Head points to the last node

       //Here, p points to the last but one node(previous node),  q points to the last   node. Then next next step is to adjust the links
        ListNode q = p.next; 

       //Last node link points to the P (last but one node)
        q.next = p; 
       //Set the last but node (previous node) next to null
        p.next = null; 
        return head; //Head points to the last node
    }

1
您能否详细说明您的答案,并提供有关您提供的解决方案的更多说明?
abarisone

1
我添加了评论。非常感谢
gurubelli

0
public void reverseLinkedList(Node node){
    if(node==null){
        return;
    }

    reverseLinkedList(node.next);
    Node temp = node.next;
    node.next=node.prev;
    node.prev=temp;
    return;
}

-1
public void reverse(){
    if(isEmpty()){
    return;
     }
     Node<T> revHead = new Node<T>();
     this.reverse(head.next, revHead);
     this.head = revHead;
}

private Node<T> reverse(Node<T> node, Node<T> revHead){
    if(node.next == null){
       revHead.next = node;
       return node;
     }
     Node<T> reverse = this.reverse(node.next, revHead);
     reverse.next = node;
     node.next = null;
     return node;
}

-1

如果有人正在寻找Scala实施,这是一个参考:

scala> import scala.collection.mutable.LinkedList
import scala.collection.mutable.LinkedList

scala> def reverseLinkedList[A](ll: LinkedList[A]): LinkedList[A] =
         ll.foldLeft(LinkedList.empty[A])((accumulator, nextElement) => nextElement +: accumulator)
reverseLinkedList: [A](ll: scala.collection.mutable.LinkedList[A])scala.collection.mutable.LinkedList[A]

scala> reverseLinkedList(LinkedList("a", "b", "c"))
res0: scala.collection.mutable.LinkedList[java.lang.String] = LinkedList(c, b, a)

scala> reverseLinkedList(LinkedList("1", "2", "3"))
res1: scala.collection.mutable.LinkedList[java.lang.String] = LinkedList(3, 2, 1)

如果被否决的人给我解释他的举动,我会很乐意改善我的回答。无论如何,它仍然在Scala中对我
有用

正是这样,下降投票者才知道,这是一个递归(实际上是尾递归)解决方案。
Venkat Sudheer Reddy Aedama 2014年

Scala不是Java,即使它们都在JVM上运行也是如此。
Bill Lynch

@sharth哇,很高兴知道这一点。您是否在打扰我的答案的第一行?
Venkat Sudheer Reddy Aedama 2014年

@VenkatSudheerReddyAedama因为最初的问题是要用Java实现,所以您对此感到不满。即使Scala在JVM中运行,这也无济于事...即使它很优雅。FWIW,我没有投票给你。
rayryeng 2014年
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.