LeetCode - 61、旋转链表

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

示例 1:

    输入: 1->2->3->4->5->NULL, k = 2

    输出: 4->5->1->2->3->NULL
解释:
    向右旋转 1 步: 5->1->2->3->4->NULL
    向右旋转 2 步: 4->5->1->2->3->NULL

示例 2:

    输入: 0->1->2->NULL, k = 4
    输出: 2->0->1->NULL
解释:
    向右旋转 1 步: 2->0->1->NULL
    向右旋转 2 步: 1->2->0->NULL
    向右旋转 3 步: 0->1->2->NULL
    向右旋转 4 步: 2->0->1->NULL

1 /**
2  * 列表定义
3  * public class ListNode {
4  *     int val;
5  *     ListNode next;
6  *     ListNode(int x) { val = x; }
7  * }
8  */

解法:

 1 class Solution {
 2     public ListNode rotateRight(ListNode head, int k) {
 3         // 去掉特殊情况
 4         if (head == null) return null;
 5         if (head.next == null) return head;
 6 
 7         // 找到尾节点,并将列表组成一个循环列表
 8         ListNode old_tail = head;
 9         int n;
10         for(n = 1; old_tail.next != null; n++) {
11             old_tail = old_tail.next;
12         }
13         old_tail.next = head;
14 
15         // 新的尾节点 : (n - k % n - 1)th node
16         // 新的头节点 : (n - k % n)th node
17         ListNode new_tail = head;
18         for (int i = 0; i < n - k % n - 1; i++) {
19             new_tail = new_tail.next;
20         }
21         ListNode new_head = new_tail.next;
22 
23         // 断开循环列表
24         new_tail.next = null;
25 
26         return new_head;
27     }
28 }
View Code

说明:先遍历一次列表,找到尾节点,将列表变更为循环列表,同时记录列表元素个数。

然后找到新的尾节点与新的头节点, 新尾节点位置(n - k % n - 1),新头节点位置(n - k % n),注意列表元素编号从0开始。

猜你喜欢

转载自www.cnblogs.com/dkccc/p/11419523.html