在类方法中递归地反转链表

时间:2017-02-23 20:22:20

标签: java recursion linked-list

我的SinglyLinkedList类中有以下实例变量。

/* head is a reference to the front of the list (first element)
 * by default, head is initialized to null */
private Node head;

/* tail is a reference to the back of the list (last element)
 * by default, tail is initialized to null */
private Node tail; 

/* length is an integer that represents the size of our list,
 * by default it is assigned a value of 0 */
protected int length;

我想要做的是编写一个名为recursiveReverse()的方法,以递归方式反转SinglyLinkedList个对象。例如list.recursiveReverse()

我有一些想法在没有传递Node对象的情况下似乎无法正常工作

public SinglyLinkedList recursiveReverse() {
    static Node temp = head;
    if(temp == null) return null;
    if(length == 1) return this;

    Node temp_2 = temp.next;
    temp.next = null;
    // here is where i am stuck with the recursive call
    // is passing a Node as an argument the only way ?
    // if so, then how do I pass it in a class method ?
    // make the method static ?
 }

1 个答案:

答案 0 :(得分:1)

这应该适合你。

public ListNode reverseList(ListNode head) {
    if(head==null || head.next == null)
        return head;

    //get second node    
    ListNode second = head.next;
    //set first's next to be null
    head.next = null;

    ListNode rest = reverseList(second);
    second.next = head;

    return rest;
}

参考:Reverse a Singly Linked List.