天天看點

leetcode刷題----反轉連結清單

<?php
/**
 * 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) {
        $cur = $head;
        $prev = null;
        while ($cur) {
            $nextNode = $cur->next;
            $cur->next = $prev;
            $prev = $cur;
            $cur = $nextNode;
        }
        return $prev;
    }
}