一. 题目描述
给定一个链表,旋转链表,将链表每个节点向右移动 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. 常规解法
结合实例,很容易想到,我们只需要找到链表向右移动 k 个位置后的分界结点,然后将其断开再重连即可。
如实例一:我们找到结点3和结点4,然后将结点3指向null,再找到结点4后面的末结点5,将5指向头结点1,即可完成算法.
public ListNode rotateRight(ListNode head, int k) {
//base cases
if (head == null || head.next == null) return head;
//find the length of linklist
ListNode nhead = head;
int len = 0;
while (nhead != null) {
++len;
nhead = nhead.next;
}
//if (k % len == 0) there is no need to rotate
if (k % len == 0) return head;
//find the last node of new linklist
k = len - (k % len) - 1;
ListNode lnode = head;
while (k > 0) {
--k;
lnode = lnode.next;
}
//find the first node of new linklist
nhead = lnode;
while (nhead.next != null) {
nhead = nhead.next;
}
//generate the new linklist
nhead.next = head;
nhead = lnode.next; // the new first node
lnode.next = null;
return nhead;
}
2. 循环链表
根据示例,我们可以先将原链表变成单循环链表,然后找到最终链表的尾结点,将其指向null,即可完成。
注意:
1. 当 k <= n ,新结点尾: (n - k)th;
2. 当 k > n , 新结点尾: n - (k % n)th;
剪枝:
如果 (k % n == 0),直接返回头结点
public ListNode rotateRight(ListNode head, int k) {
//base cases
if (head == null || head.next == null) return head;
//generate the circulate list
ListNode old_tail = head;
int n;
for (n = 1; old_tail.next != null; n++) {
old_tail = old_tail.next;
//old_tail.next = head;
}
//pruning
if (k % n == 0) return head;
else old_tail.next = head;
//find the new tail node
k = n - (k % n);
ListNode new_tail = old_tail;
while (k > 0) {
--k;
new_tail = new_tail.next;
}
ListNode new_head = new_tail.next;
new_tail.next = null; //let the new_head point to null
return new_head;
}
三. 总结
其实两种方法殊途同归,链表算法主要就是在写代码的时候要防止空指针异常,慢慢解决就好了。