《leetCode-php》旋转链表

本文介绍了一种链表旋转算法,该算法将给定链表向右旋转k个位置,通过计算链表长度并进行节点调整实现。以1->2->3->4->5->null为例,当k=2时,链表将变为4->5->1->2->3->null。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

将给定的链表向右转动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;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值