-
Notifications
You must be signed in to change notification settings - Fork 86
/
Copy pathRotateList
41 lines (40 loc) · 986 Bytes
/
RotateList
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/* Given the head of a linked list, rotate the list to the right by k places.
Input: head = [1,2,3,4,5], k = 2
Output: [4,5,1,2,3]
*/
/**
* 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)return head;
ListNode temp=head;
int length=0,a;
while(temp!=null)
{
temp=temp.next;
length++;
}
if(k%length==0)return head;
a=k%length;
ListNode start=head,mid=head,join=head,ans=head;
while(join.next!=null)join=join.next;
int x=length-a;
while(x--!=1)
{
mid=mid.next;
ans=ans.next;
}
ans=ans.next;
mid.next=null;
join.next=start;
return ans;
}
}