LeetCode No61. 旋转链表

题目

给你一个链表的头节点 head ,旋转链表,将链表每个节点向右移动 k 个位置。

示例 1:

输入:head = [1,2,3,4,5], k = 2
输出:[4,5,1,2,3]

示例 2:

输入:head = [0,1,2], k = 4
输出:[2,0,1]

提示:

链表中节点的数目在范围 [0, 500] 内
-100 <= Node.val <= 100
0 <= k <= 2 * 10^9

思路

用的笨办法,截取链表。

AC代码

点击查看代码
/**
 * 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 || k == 0) {
            return head;
        }
        ListNode oldNode = head;
        int len = 1;
        while( oldNode.next!=null ) {
            oldNode = oldNode.next;
            len ++;
        }
        oldNode.next = head;
        ListNode newNode = head;
        for(int i=0; i<len-k%len-1; i++) {
            newNode = newNode.next;
        }
        ListNode newHead = newNode.next;
        newNode.next = null;
        return newHead;
    }
}
posted @ 2022-06-09 22:18  Asimple  阅读(18)  评论(0编辑  收藏  举报