题目
给出一个链表,将链表旋转到右边的第k个位置,其中k是非负的。
例1:
输入: 1->2->3->4->5->NULL, k = 2
输出:4->5->1->2->3->NULL
例2:
输入: 0->1->2->NULL, k = 4
输出:2->0->1->NULL
解释 :
rotate 1 steps to the right: 2->0->1->NULL
rotate 2 steps to the right: 1->2->0->NULL
rotate 3 steps to the right: 0->1->2->NULL
rotate 4 steps to the right: 2->0->1->NULL
代码块
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode rotateRight(ListNode head, int k) {
if(head == null || head.next == null) return head;
int len = 1;
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode fastNode = head;
while(fastNode.next != null){//这个判断条件是关键。
fastNode = fastNode.next;
len++;
}
ListNode slowNode = head;
for(int i = 0; i < len - k%len - 1; i++){
slowNode = slowNode.next;
}
fastNode.next = dummy.next;
dummy.next = slowNode.next;
slowNode.next = null;
return dummy.next;
}
}
代码分析
本题的代码分为3部分。
第一是计数,即链表的长度。
第二是找到要旋转的结点的位置分界线,即看它在原链表中的前置节点(为新链表的头结点)。
第三是交换顺序。
注意:k如果超过链表的长度,需要进行模运算。
遇到的问题: 计数时判断条件搞错了。写成head(head.next)!=null
,这是不对的,因为head是不会变的。fastNode会变。有点混乱。
ListNode fastNode = new ListNode(0);
fastNode = head;
等价于
ListNode fastNode = head;
然后就是默写LeetCode的时候第一句就判断错了,应该是== null 返回head;自己写成了非等。失误。