LeetCode第61题:旋转链表(中等)

LeetCode第61题:旋转链表(中等)

  • 题目:给定一个链表,旋转链表,将链表每个节点向右移动 k 个位置,其中 k 是非负数。
  • 解法一:因为声明了first和second两个节点进行移动(我不知道怎么变成一个节点移动),就把0个、1个、2个节点在最前面都特殊讨论了。
class Solution {
    public ListNode rotateRight(ListNode head, int k) {
        if(k == 0 || head == null || head.next == null) return head;
        ListNode first = head.next;
        if(first.next == null){
            if(k%2 == 0){
                return head;
            }else{
                head.next = null;
                first.next = head;
                head = first;
                return head;
            }
        }
        int j = 2;
        while(first.next != null){
                first = first.next;
                j++;
        }
        k = k%j;
        for(int i=0;i<k;i++){
            first = head.next;
            ListNode second = first.next;
            while(second.next != null){
                first = second;
                second = first.next;
            }
            first.next = null;
            second.next = head;
            head = second; 

        }
        return head;
    }
}

在这里插入图片描述

  • 解法二:想法比较巧妙,把链表变成一个封闭的环,再判断在哪里断开。
class Solution {
  public ListNode rotateRight(ListNode head, int k) {
    // base cases
    if (head == null) return null;
    if (head.next == null) return head;

    // close the linked list into the ring
    ListNode old_tail = head;
    int n;
    for(n = 1; old_tail.next != null; n++)
      old_tail = old_tail.next;
    old_tail.next = head;

    // find new tail : (n - k % n - 1)th node
    // and new head : (n - k % n)th node
    ListNode new_tail = head;
    for (int i = 0; i < n - k % n - 1; i++)
      new_tail = new_tail.next;
    ListNode new_head = new_tail.next;

    // break the ring
    new_tail.next = null;

    return new_head;
  }
}

作者:LeetCode
链接:https://leetcode-cn.com/problems/rotate-list/solution/xuan-zhuan-lian-biao-by-leetcode/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值