天天看点

leetcode-61-旋转链表

61. 旋转链表

给你一个链表的头节点

head

,旋转链表,将链表每个节点向右移动

k

个位置。

示例 1:

leetcode-61-旋转链表
输入:head = [1,2,3,4,5], k = 2
输出:[4,5,1,2,3]
           

示例 2:

leetcode-61-旋转链表
输入:head = [0,1,2], k = 4
输出:[2,0,1]
           

提示:

  • 链表中节点的数目在范围

    [0, 500]

  • -100 <= Node.val <= 100

  • 0 <= k <= 2 * 109

解题思路

​ 首先进行一个常规的非空的判断,然后开始我们的题解。先统计链表中的节点个数,count的初值为1,遍历递增,在遍历完后cur也维护了最后一个节点,之后对偏移量取模,在k>count时可以减少偏移数。之后通过count-k在原链表中位置是旋转后链表头结点的前一个,获取preNode。之后将之前cur指向原链表的头结点,头结点指向preNode的下一个节点,然后preNode.next指向null,返回head

leetcode-61-旋转链表
代码
class Solution {
    public ListNode rotateRight(ListNode head, int k) {
        if(head==null || k==0) return head;
        //统计节点个数
        int count = 1;
        ListNode cur = head;
        while(cur.next!=null){
            cur = cur.next;
            count++;
        }

        k = k%count;
        int pre = count - k;
        ListNode preNode = head;
        while(pre>1){
            preNode = preNode.next;
            pre--;
        }

        cur.next = head;
        head = preNode.next;
        preNode.next= null;
        return head;


    }
}