206. Reverse Linked List (1)

Link

Solution

先記住下一個 (next)以便下次開始

然後改變next的方向 本來是 1->2 ,改成2->1

class Solution {
    public ListNode reverseList(ListNode head) {
         /* iterative solution */
        ListNode prevHead = null;
        while (head != null) {
            ListNode next = head.next; // keep the orgin next
            head.next = prevHead;
            prevHead = head;
            head = next; // keep the orgin next
        }
        return prevHead;
    }
}
class Solution {
    public ListNode reverseList(ListNode head) {
        return recursiveRever(head, null);
    }
    
    public ListNode recursiveRever(ListNode node, ListNode newHead){
        if(node == null){
            return newHead;
        }
        ListNode next = node.next;
        node.next = newHead;
        return recursiveRever(next, node);
    }
}

Last updated

Was this helpful?