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)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

在这里插入图片描述

发布了79 篇原创文章 · 获赞 7 · 访问量 1377

猜你喜欢

转载自blog.csdn.net/new_whiter/article/details/104248711