Rotate List LeetCode Java

本文介绍了一种链表右旋转算法的实现方法。通过遍历链表获取长度,并利用快慢指针技巧,在O(n)时间内完成指定位置的旋转操作。

描述
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->nullptr and k = 2, return 4->5->1->2->3->nullptr.
分析
先遍历一遍,得出链表长度 len,注意 k 可能大于 len,因此令 k% = len。将尾节点 next 指针
指向首节点,形成一个环,接着往后跑 len − k 步,从这里断开,就是要求的结果了。

代码

 1 public static ListNode rotateRight(ListNode head, int n) {
 2         if (head == null || head.next == null || n == 0)
 3             return head;
 4         ListNode fast = head, slow = head, countlen = head;
 5         ListNode newhead = new ListNode(-1);
 6         int len = 0;
 7 
 8         while (countlen != null) {
 9             len++;
10             countlen = countlen.next;
11         }
12 
13         n = n % len;
14         if (n == 0)
15             return head;
16         for (int i = 0; i < n; i++) {
17             fast = fast.next; // slow与fast间隔n+1
18         }
19         while (fast.next != null) {
20             slow = slow.next; // slow指向要倒着数的开始点的前一个位置。
21             fast = fast.next;
22 
23         }
24 
25         newhead = slow.next;
26         fast.next = head;
27         slow.next = null;
28 
29         return newhead;
30     }

 

转载于:https://www.cnblogs.com/ncznx/p/9160842.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值