《leetCode-php》旋转链表

将给定的链表向右转动k个位置,k是非负数。
例如:
给定1->2->3->4->5->null , k=2,
返回4->5->1->2->3->null。

<?php
class Node {
    public $next = null;
    public $val;
    public function __construct($val) {
        $this->val = $val;
    }
}
function rotateRight($head, $k) {
    $len = 0;
    $node = $head;
    while ($head != null) {
        $len ++;
        $pre  = $head;
        $head = $head->next;
    }
    $pre->next = $node;
    for ($i = 0; $i < $len - $k; $i ++) {
        $pre = $pre->next;
    }
    $retNode = $pre->next;
    $pre->next = null;
    return $retNode;
}
$node1 = new Node(1);
$node2 = new Node(2);
$node3 = new Node(3);
$node4 = new Node(4);
$node1->next = $node2;
$node2->next = $node3;
$node3->next = $node4;
$ret = rotateRight($node1, 2);
while ($ret != null) {
    print $ret->val;
    $ret = $ret->next;
}
发布了284 篇原创文章 · 获赞 32 · 访问量 49万+

猜你喜欢

转载自blog.csdn.net/less_cold/article/details/103221749