代码拉取完成,页面将自动刷新
package pers.vic.basics.leetcode;
import com.sun.org.apache.bcel.internal.generic.IF_ACMPEQ;
/**
* @description: 61. 旋转链表 {@literal https://leetcode-cn.com/problems/rotate-list/}
* @author Vic.xu
* @date: 2020/12/23 0023 8:26
*/
public class J0061_M_RotateRight {
/*
给定一个链表,旋转链表,将链表每个节点向右移动 k 个位置,其中 k 是非负数。
*/
/**
* 1. 先得到链表的长度,计算出偏移量,计算出新尾部节点的位置
* 2. 把原链表尾首相连
* 3. 遍历原来的链表,到新尾部的时候,把它的后面的节点作为头节点返回,并把此尾节点的next置为空
*/
public static ListNode rotateRight(ListNode head, int k) {
if (head == null || head.next == null || k == 0) {
return head;
}
ListNode cur = head.next;
ListNode tail = null;
int size = 1;
while (cur != null) {
ListNode next = cur.next;
//cur节点是tail节点的时候
if (next == null) {
tail = cur;
}
cur = next;
size++;
}
//计算偏移量
int offset = k % size;
if (offset == 0) {
return head;
}
//收尾相接起来
tail.next = head;
//新的尾部节点在哪个位置
int newTailLocation = size - offset ;
ListNode node = head;
int num = 0;
while (node != null) {
num++;
//遍历到需要标志的尾部节点的节点
if (num == newTailLocation){
ListNode curTail = node;
ListNode newHead = node.next;
curTail.next = null;
return newHead;
}
node = node.next;
}
return head;
}
public static void main(String[] args) {
ListNode head = new ListNode(new int[]{1,2});
System.out.println(head);
ListNode listNode = rotateRight(head, 2);
//4->5->1->2->3->NULL
System.out.println(listNode);
}
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。