将一个链表m位置到n位置之间的区间反转,要求使用原地算法,并且在一次扫描之内完成反转。
例如:
给出的链表为1->2->3->4->5->NULL, m = 2 ,n = 4,
返回1->4->3->2->5->NULL.
注意:
给出的m,n满足以下条件:
1 ≤ m ≤ n ≤ 链表长度
<?php
class Node {
public $next = null;
public $val;
public function __construct($val) {
$this->val = $val;
}
}
function reverseBetween($head, $m, $n) {
$pre = null;
$rePre = null;
$headPre = null;
while (true) {
if ($m == 1) {
if ($n == 1) {
//反转结束点
$headPre->next = $head;
$pre->next = $rePre;
break;
}
//反转链表
$next = $head->next;
$head ->next = $rePre;
$rePre = $head;
$head = $next;
$n --;
} else {
//寻找反转链表的位置
$m --;
$pre = $head;//获取m前的节点
$head = $head->next;
$headPre = $head;//获取开始反转的点
}
}
}
$node1 = new Node(1);
$node2 = new Node(2);
$node3 = new Node(3);
$node4 = new Node(4);
$node5 = new Node(5);
$node1->next = $node2;
$node2->next = $node3;
$node3->next = $node4;
$node4->next = $node5;
reverseBetween($node1, 2, 4);
$head = $node1;
while(!is_null($head)) {
print $head->val . "\n";
$head = $head->next;
}