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->NULL and k = 2,
return 4->5->1->2->3->NULL.
题意是链表向右偏移k位。自己开始理解错题意,以为是每隔k位反转一次。
考虑参数k可能的情况:1、k小于0不合法;2、k等于0,直接返回;3、k大于0,小于链表长度,右移k位;4、k大于0且大于链表长度len,则需要右移k%len位。
右移的关键步骤:1、求得链表长度len,根据len更新k;2、将链表结尾的next指向链表头部;2、找到新链表的头结点;3、将新链表尾结点的next置为null。
public ListNode rotateRight1(ListNode head, int k) {
if (head == null || head.next == null || k == 0) {
return head;
}
int len = 0;
ListNode dummy = head;
ListNode last = null;
while (dummy != null) {
len++;
last = dummy;
dummy = dummy.next;
}
k = k % len;
if (k == 0) {
return head;
}
int cnt = 0;
dummy = head;
ListNode newHead = null;
while (dummy != null) {
cnt++;
if (cnt == len - k) {
newHead = dummy.next;
dummy.next = null;
break;
} else {
dummy = dummy.next;
}
}
last.next = head;
return newHead;
}