剑指offer-反转链表-php

来源:互联网 发布:office for mac 安装 编辑:程序博客网 时间:2024/06/09 16:24

题目

输入一个链表,反转链表后,输出链表的所有元素。

题解

上图。
先保存下一个节点,再让这个节点下一个指向上一个。然后依次遍历后边的。

代码

<?php/*class ListNode{    var $val;    var $next = NULL;    function __construct($x){        $this->val = $x;    }}*/function ReverseList($pHead){    if($pHead == NULL)        return NULL;    $cur  = null;    $pre  = null;    while($pHead != null){        $tmp = $pHead->next;        $pHead->next = $pre;        $pre = $pHead;        $pHead = $tmp;    }    return $pre;}
0 0