[leetcode]61. Rotate List@Java解题报告

本文详细解析了LeetCode上的一道经典题目:旋转链表。文章介绍了如何通过一次遍历找到链表长度,并据此确定旋转位置,实现链表的高效旋转。通过具体的代码示例,展示了如何将链表分为两部分并进行重新连接。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

https://leetcode.com/problems/rotate-list/description/

Given a list, rotate the list to the right by k places, where k is non-negative.

For example:
Given 1->2->3->4->5->NULL and k = 2,
return 4->5->1->2->3->NULL.




这道题主要先理解题意,就是倒着数k个node,从那开始到结尾和之前那部分对调,那个例子就是,4->5拿前面来,1->2->3拿后面去。



package go.jacob.day817;

/**
 * 61. Rotate List
 * @author Jacob
 */
public class Demo2 {
	/*
	 * 这种方法考虑了k=0的情况。
	 * 当k=0,cur和pre都为链表最后一个节点
	 * 运行cur.next = preHead.next;preHead.next = pre.next;pre.next = null;后
	 * 链表结构没有改变
	 */
	public ListNode rotateRight(ListNode head, int k) {
		if (k == 0 || head == null || head.next == null)
			return head;
		ListNode preHead = new ListNode(0);
		preHead.next = head;
		ListNode cur = head;
		ListNode pre = head;
		int total;
		for (total = 1; cur.next != null; total++)
			cur = cur.next;
		for (int i = 1; i < total - k % total; i++) {
			pre = pre.next;
		}
		cur.next = preHead.next;
		preHead.next = pre.next;
		pre.next = null;

		return preHead.next;
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值