leetcode刷题(单链表)6—旋转链表

61. 旋转链表

给定一个链表,旋转链表,将链表每个节点向右移动 k 个位置,其中 k 是非负数。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    
    
    // 执行用时:1 ms, 在所有 Java 提交中击败了89.54%的用户
    // 内存消耗:39.2 MB, 在所有 Java 提交中击败了91.52%的用户
    public ListNode rotateRight(ListNode head, int k) {
    
    
        int len = 0;
        ListNode p = head;
        ListNode tail = p;
        //先找到整个链表长度
        //并且记录链表尾部
        while(p != null){
    
    
           
            ++len;
            tail = p;
            p = p.next;
        }
        //考虑空链表和不需要移动的情况
        if(len == 0 || k == 0)
         return head;
        //将首尾相连
        tail.next = head;
        p = head;
        k %= len;
        //找到移动后的首部
        for(int i = 0; i < len - k;++i){
    
    
            tail = p;
            p = p.next;
        }
        head = p;
        tail.next = null;
        return head;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_38754625/article/details/108536885