1. 首页
  2. 软件开发
  3. day-29 旋转链表

day-29 旋转链表

  • 发布于 2024-09-26
  • 1 次阅读


思路
找到需要返回的链表的头结点,将其断开为两个链表,再拼接起来即可。例如链表长度为len,那么第len-k个元素即为头结点

解题方法
因为0 <= k <= 2 * 109,所以先将k对len取模

Code

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {

    public ListNode rotateRight(ListNode head, int k) {

        if(head==null) return head;
        int len=0;
        ListNode t=head;
        while(t!=null){

            len++;
            t=t.next;
        }
        k=k%len;//防止k超过链表长度
        if(k==0) return head;
        int tt=len-k;
        t=head;
        ListNode ans=null;
        while(tt>0){

            if(tt==1){

                ans=t.next;//需要返回的链表的头结点
                t.next=null;
                tt--;
            }else{

                t=t.next;
                tt--;
            }
        }
        t=ans;
        while(t.next!=null){

            t=t.next;
        }
        t.next=head;
        return ans;
    }
}

原文链接: https://blog.csdn.net/qq_53568730/article/details/138488306