旋转链表

问题描述

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

解决思路

题目其实翻译成对链表进行向右移位 k 位,感觉会合适一点。比如输入链表:
1-2-3-4-5-null, k=2
向右移 1 位:5-1-2-3-4-null;
向右移 2 位:4-5-1-2-3-null;
输出:4-5-1-2-3-null

  
*   找找规律,发现不管移位多少次,其实只用管「 k % 链表长度 = z 」 的次数;
*    需要找到旧链表尾节点 和 新链表的尾部,连接起来即可。
*    空间复杂度O(n),空间复杂度O(1),只需要开辟常数空间。

Java 代码

 1 public class Solution {
 2     public ListNode rotateRight(ListNode head, int k) {
 3         if (head == null ) return null;
 4         ListNode first = head;
 5         ListNode second = head;
 6         int z = k % getLen(head);
 7         while (z>0) {
 8             first = first.next;
 9             z--;
10         }
11         while (first.next != null) {
12             first = first.next;
13             second = second.next;
14         }
15 
16         first.next = head;
17         ListNode newH = second.next;
18         second.next = null;
19         return newH;
20     }
21 
22     private int getLen(ListNode head) {
23         int ret=0;
24         while(head !=null) {
25             ret += 1;
26             head = head.next;
27         }
28         return ret;
29     }
30 }


 
原文地址:https://www.cnblogs.com/dogeLife/p/11181092.html