-
Notifications
You must be signed in to change notification settings - Fork 49
/
rotateList.java
61 lines (51 loc) · 1.43 KB
/
rotateList.java
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
//Given the head of a linked list, rotate the list to the right by k places.
/**
* 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 int findSize(ListNode head){
int size = 0;
ListNode curr = head;
while(curr!= null){
curr= curr.next;
size++;
}
return size;
}
public ListNode rotateRight(ListNode head, int k) {
if (head == null || head.next == null){
return head;
}
int size = findSize(head);
int rem = k%size;
if(rem==0) return head;
int travel = size-rem;
ListNode curr = head;
ListNode first = head;
//last node of first list
int i =1;
while(i<travel){
curr =curr.next;
i++;
}
//Store the second list
ListNode temp = curr.next;
//finishing first list
curr.next = null;
//Traverse to the end of second list to point it to the start of first list
curr = temp;
while(curr.next!=null){
curr = curr.next;
}
curr.next=first;
head = temp;
return head;
}
}