Recursion is very simple.
public ListNode rotateRight(ListNode head, int n) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
if (head==null || head.next == null) return head;
if (n==0) return head;
ListNode curr = head;
ListNode prev = head;
while (curr.next != null) {
prev = curr;
curr = curr.next;
}
curr.next = head;
prev.next = null;
return rotateRight(curr, n-1);
}
1. n may be larger than the length of list.
2. Non-recursion
public ListNode rotateRight(ListNode head, int n) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
if (head==null || head.next ==null) return head;
ListNode dummy = new ListNode(0);
dummy.next = head;
int len = listLen(head);
n%=len;
ListNode p = dummy, q = dummy;
int i=0;
while (q.next != null) {
if (i>=n) {
p=p.next;
}
q=q.next;
i++;
}
q.next = dummy.next;
dummy.next = p.next;
p.next = null;
return dummy.next;
}
private int listLen(ListNode p) {
int len = 0;
while (p != null) {
len++;
p = p.next;
}
return len;
}
No comments:
Post a Comment