力扣刷题61. 旋转链表

力扣刷题61. 旋转链表_第1张图片
设链表的长度为n,如果移动n次,则会恢复成原位。所以每次移动只需移动(k%n)次即可。

思路为首先将链表形成环,然后找到断开的节点。

/**
 * 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 || head.next == null){return head;}
        if(k == 0){return head;}
        ListNode tail = head;
        int n = 1;
        //首先找到链表最后一个节点,并且统计链表长度
        while(tail.next != null){
           tail = tail.next;
           n++;
        }
        tail.next = head;
        ListNode newTail = head;
        for(int i = 0; i<(n-1-k%n); i++){
           newTail = newTail.next;
        }
        //新的头节点指向环断开的位置
        ListNode newHead = newTail.next;
        newTail.next = null;
        return newHead;
    }
}

注意n的初始值要设为1.

你可能感兴趣的:(leetcode刷题,链表,leetcode,数据结构)