<?php
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
* @param Integer $k
* @return ListNode
*/
function reverseKGroup($head, $k) {
if ($head == null) return $head;
//建立头节点
$pre = new ListNode(0, $head);
$cur = $pre;
$end = $pre;
while ($end->next != null) {
//判断是否长度达到k了
for ($i = 0; $i < $k; $i++) {
$end = $end->next;
if ($end == null) break 2;
}
$start = $pre->next;
$next = $end->next;
//断开$head的链接 开始反转
$end->next = null;
//k个链表反转并链接
$pre->next = $this->reverse($start);
//重新链接
$start->next = $next;
$pre = $start;
$end = $pre;
}
return $cur->next;
}
//翻转链表
function reverse($head) {
$pre = null;
$cur = $head;
while ($cur != null) {
$back = $cur->next;
$cur->next = $pre;
$pre = $cur;
$cur = $back;
}
return $pre;
}
}
$a1 = new ListNode(0);
$c = $a1;
for($i=1;$i<10;$i++){
$t = new ListNode($i);
$c->next = $t;
$c = $t;
}
$b = (new Solution())->reverseKGroup($a1,2);
while (true){
var_dump($b->val);
if($b->next){
$b = $b->next;
}else{
break;
}
}
每K个反转链表
于 2022-03-03 12:29:24 首次发布