This is No.61 in leetcode.
The description:
Given a linked list, rotate the list to the right by k places, where k is non-negative.
This is my original solution:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode rotateRight(ListNode head, int k) {
if (k == 0){
return head;
}
//ListNode tail = head;
ListNode cur = head;
// cur -> 3
int count = 1;
while (count <= k && cur != null)
{
cur = cur.next;
count++;
}
if (cur == null){
return head;
}
ListNode tail = cur;
while(cur.next != null){
cur = cur.next;
}
/*
// tail -> 4
tail = cur.next;
// 1 - 2 - 3 - 4 - 5 - 1
tail.next = head;
//4 - 5 - 1 - 2 - 3
cur.next = NULL;
*/
cur.next = head;
head = tail.next;
tail.next = null;
return head;
}
}
It could pass some tests, but here is a wrong case when the k is greater than the length of list, for example:
Input
[0,1,2]
4
Output
[0,1,2]
Expected
[2,0,1]
Then I fix my code as below:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode rotateRight(ListNode head, int k) {
if(head == null || k == 0) {
return head;
}
ListNode cur = head;
int len = 1;
while(cur.next != null) {
cur = cur.next;
len++;
}
cur.next = head;
k %= len;
for(int i = 0; i < len - k; i++) {
cur = cur.next;
}
head = cur.next;
cur.next = null;
return head;
}
}
Then it works.
By the way, here are two takeaways:
- use node.next rather than node->next in java.
- remember to use remainder.