在面试百度实习生的 时候遇到了这个问题,不是太难,当时只给面试官叙述了一下思路,后来想起这个问题仍是决定手撸一遍,要否则总数眼高手低,昨天连快排都撸不出来了。。。php
题目简介:没什么能够过多介绍的,就是实现一个链表的反转面试
<?php class Node { public $value; public $next = null; public function __construct($data) { $this->value = $data; } } /** * 构建链表 * @param $vals array 链表值的数组 * @return Node */ function genLinkList($vals) { $headVal = array_shift($vals); $head = new Node($headVal); $p = $head; foreach ($vals as $val) { $p->next = new Node($val); $p = $p->next; } return $head; } /** * 反转链表 * @param $head Node 链表头结点 * @return Node 反转后的链表头结点 */ function revLinkList($head) { $h = $head; if (!$h->next) { return $head; } $n = $h->next; while ($n) { $nn = $n->next; $n->next = $h; $h = $n; $n = $nn; } $head->next = null; return $h; } $data = [1, 2, 3, 4, 5, 6, 7]; $linkList = genLinkList($data); print_r($linkList); $linkListRev = revLinkList($linkList); print_r($linkListRev);