61. Rotate List(旋转链表)

本文介绍了一种链表旋转算法,通过两种方法实现链表的右旋。第一种方法通过多次调用一次旋转函数来完成旋转,但效率较低;第二种方法通过将链表闭合成环,再断开新尾节点和新头节点前的连接,实现了更高效的链表旋转。

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

题目描述

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

Example 1:

Input: 1->2->3->4->5->NULL, k = 2
Output: 4->5->1->2->3->NULL
Explanation:
rotate 1 steps to the right: 5->1->2->3->4->NULL
rotate 2 steps to the right: 4->5->1->2->3->NULL

Example 2:

Input: 0->1->2->NULL, k = 4
Output: 2->0->1->NULL
Explanation:
rotate 1 steps to the right: 2->0->1->NULL
rotate 2 steps to the right: 1->2->0->NULL
rotate 3 steps to the right: 0->1->2->NULL
rotate 4 steps to the right: 2->0->1->NULL

方法思路

Approach1:

class Solution {
    public ListNode rotateRight(ListNode head, int k) {
        //Runtime: 8054 ms, faster than 5.01%
        //Memory Usage: 38.7 MB
       if(head == null || head.next == null)
           return head;
        while(k > 0){
        head = rotateOnceTime(head);
            k--;
        }
        return head;
    }
    public ListNode rotateOnceTime(ListNode head){
       // ListNode con = head;
        ListNode cur = head;
        while(cur.next.next != null)
            cur = cur.next;
        // 循环结束后,cur 为尾部倒数第二个结点
        ListNode tail = cur.next;
        cur.next = cur.next.next;//令cur成为尾结点
        tail.next = head;//tail结点成为头结点
        return tail;
    }
}

Approach2:

The nodes in the list are already linked, and hence the rotation basically means

To close the linked list into the ring.

To break the ring after the new tail and just in front of the new head.
class Solution {
    //Runtime: 6 ms, faster than 100.00%
    //Memory Usage: 38.1 MB, less than 20.71%
  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;//step1、2
    // n 为链表的长度
    // find new tail : (n - k % n - 1)th node;实际上是(n - k % n)th node
    // and new head : (n - k % n)th node;实际上是(n - k % n + 1)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;//step3、4

    return new_head;
  }
}

Complexity Analysis

Time complexity : O(N)  where Nis a number of elements in the list.

Space complexity : O(1) since it's a constant space solution.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值