1 Star 0 Fork 0

临窗旋墨/basics

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
J0061_M_RotateRight.java 2.09 KB
一键复制 编辑 原始数据 按行查看 历史
临窗旋墨 提交于 2020-12-24 17:59 . leetcode :61. 旋转链表
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);
}
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Java
1
https://gitee.com/xuqiudong/basics.git
git@gitee.com:xuqiudong/basics.git
xuqiudong
basics
basics
master

搜索帮助

A270a887 8829481 3d7a4017 8829481