Leetcode 旋转链表

旋转链表

题目描述:

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

题目链接

/**
 * 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) {
    
    
        int len = 0;
        ListNode temp = head;
        List<ListNode> nodes = new ArrayList<ListNode>();
        while(temp != null){
    
    
            nodes.add(temp);
            temp = temp.next;
        }
        len = nodes.size();
        if(len == 0) return head; // 由于整除可能会出现除以0的情况
        k = k%len;
        if(k == 0) return head; // 此时不需要改变顺序
        head = nodes.get(len - k);
        temp = nodes.get(len - 1); // 右边连接的最后一个
        temp.next = nodes.get(0); // 连接左边的第一个
        nodes.get(len - k - 1).next = null; // 防止闭环
        
        return head;
    }
}

首先直接放入数组中,然后按照题目逻辑进行操作即可。

猜你喜欢

转载自blog.csdn.net/weixin_43914658/article/details/113797055