[LeetCode] #206: Reverse Linked List (递代&递归解法)

386 查看

原题:

Reverse a singly linked list.

click to show more hints.

Hint:
A linked list can be reversed either iteratively or recursively. Could you implement both?

既然问了能否iteratively or recursively, 那就both把.

iterative 解法:

总结就是得到下一个节点,更改当前节点指向,将指针往下移动,直到过完整个linkedlist.

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode prev = null;
        ListNode cur = head;
        while(cur!=null){
            ListNode next = cur.next; 
            cur.next = prev;
            prev = cur;
            cur = next;
        }
        return prev;
    }
}

recursive 解法:

总结是传给helper method两个节点,cur和pre(最开始是head和null), 先用n1存当前节点的next,然后把当前节点的next指向pre,然后一直recursively call help method直到过完整个linkedlist.

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode reverseList(ListNode head) {
        if(head == null||head.next== null)
            return head;
        return getReverse(head, null);
    }
    
    public ListNode getReverse(ListNode cur, ListNode prev){
        if(cur.next == null){
            cur.next = prev;
            return cur;
        }
        ListNode n1 = cur.next;
        cur.next = prev;
        return getReverse(n1,cur);
    }
}