在Java中递归地反转链表

时间:2013-01-29 23:48:35

标签: java linked-list singly-linked-list

我有两个课程,ListNodeMyList

ListNode:

public class ListNode {
    private String str;
    private ListNode next;
    public ListNode(String str) {
        this.str = str;
        next = null;
    }
    public String getString() {
        return str;
    }
    public ListNode getNext() {
        return next;
    }
    public void setNext(ListNode next) {
        this.next = next;
    }
}

MYLIST

public MyList RecReverse() { //my attempt at the recursive method
    if (head.getNext() == null) {
        return this;
    }
    MyList remainder = new MyList();
    remainder.head = head.getNext(); //start rest of list at the 2nd thing
    ListNode temp = new ListNode(head.getString()); //get the first thing in list
    temp.setNext(null); //set to null to indicate end of list

    remainder.RecReverse(); //reverse the remaining things in the list
    remainder.head.setNext(temp); //then add it to the end of the reversed list

    return remainder;



}

因为您可以看到MyList类有一个我们需要使用的ListNode变量。要求RecReverse方法不带参数并返回MyList对象。该方法还必须使用函数Rev(L) = Rev(L`).x,其中L`是列表的其余部分,x是列表中的第一个内容。

目前,当我反转列表并打印时,它只打印以下内容:

  

2

     

一个

控制台中的

2 个答案:

答案 0 :(得分:2)

public MyList RecReverse() { //my attempt at the recursive method
    if (head.getNext() == null) {
        return this;
    }

    MyList remainder = new MyList();
    remainder.head = head.getNext(); // New list has rest of this list (after head)
    ListNode temp = new ListNode(head.getString()); // save the first thing in list

    remainder = remainder.RecReverse(); //reverse the things in the new 2nd part list

    remainder.end().setNext(temp); // put old head on the end

    return remainder;

}

private ListNode end() {
    ListNode curr = head;
    while (curr.getNext() != null) {
        curr = curr.getNext();
    }
    return curr;
}

答案 1 :(得分:1)

如果您以某种方式设法保留原始列表的尾部,您将获得正确的结果。问题是,在每次递归调用中,您组装了正确的列表,但返回包含2个元素的列表。请参阅Lee Meador对正确解决方案的回答;如果你把结尾放在列表结构中,你可以优化它。