Rotate List 部分旋转链表

Given a list, rotate the list to the right by k places, where k is non-negative.

For example:
Given 1->2->3->4->5->NULL and k = 2,
return 4->5->1->2->3->NULL.

我们先考虑通用的情况:

对于k, 我们希望找到2个指针,最终能指在3, 5 这个位置,假设指向3的为slow, 指向5的为fast。

那么,newHead = slow.next ( 4 为head了 )

slow.next = null (从3这里断开了)

fast.next = head; ( 5指向原来的head)

这样就能形成:4->5->1->2->3->NULL 了。

如何能找到这样的2个指针。我们首先要明白,这2指针的间距为k。所以:

1. 先让slow, fast 都指向head

2. 让fast先走k步。

3. 让fast 跟 slow 一样走,当fast.next = null 的时候可以停下来了。

在得到通用的情况以后,还有一些边界问题需要解决:

1. head = null

2. k = 0  (此时不需要逆转的)

3. k > list的长度n ( 这个时候要取 k = k % n )

解决了上述这些问题后,就可以了。

复杂度:
时间复杂度:O ( n )
空间复杂度:O ( 1 )

时间:

代码:

    public ListNode rotateRight(ListNode head, int k) {
        if (head == null) {
            return head;
        }
        int n = listLength(head);
        k = k % n;
        if (k == 0) {
            return head;
        }
        ListNode fast = head, slow = head;
        for (int i = 0; i < k; i++) {
            fast = fast.next;
        }
        while (fast.next != null) {
            fast = fast.next;
            slow = slow.next;
        }
        ListNode newHead = slow.next;
        slow.next = null;
        fast.next = head;
        return newHead;
    }

    private int listLength(ListNode head) {
        int count = 0;
        while (head != null) {
            head = head.next;
            count++;
        }
        return count;
    }


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值