算法:链表反转

在面试百度实习生的 时候遇到了这个问题,不是太难,当时只给面试官叙述了一下思路,后来想起这个问题还是决定手撸一遍,要不然总数眼高手低,昨天连快排都撸不出来了。。。

题目简介:没什么可以过多介绍的,就是实现一个链表的反转

<?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);
posted @ 2018-04-22 15:12  jeferwang  阅读(228)  评论(0编辑  收藏  举报