206. Reverse Linked List

/**
 * Definition for a singly-linked list.
 * class ListNode {
 *     public $val = 0;
 *     public $next = null;
 *     function __construct($val = 0, $next = null) {
 *         $this->val = $val;
 *         $this->next = $next;
 *     }
 * }
 */
class Solution {

    /**
     * @param ListNode $head
     * @return ListNode
     */
    function reverseList($head) {
        $newHead = null; // 最後一個 next
        while($head !== null) {
            // 暫存下一步
            $next = $head->next;
            // 讓每一個 head 的 next 都指向前一個
            // 1 > 2 > 3 > 4 > 5 => 1 < 2 < 3 < 4 < 5
            $head->next = $newHead;
            $newHead = $head;
            // 切換到下一步
            $head = $next;
        }

        return $newHead;
    }
}

Last updated