-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathRotateLinkedList.java
More file actions
45 lines (40 loc) · 958 Bytes
/
RotateLinkedList.java
File metadata and controls
45 lines (40 loc) · 958 Bytes
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
/**
* Definition for singly-linked list.
* class ListNode {
* public int val;
* public ListNode next;
* ListNode(int x) { val = x; next = null; }
* }
*/
/**
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.
**/
public class Solution {
public ListNode rotateRight(ListNode A, int B) {
ListNode current = A;
int count = 1;
if(current.next == null)
{
return current;
}
while(current.next != null)
{
current = current.next;
count++;
}
current.next = A;
int length = count - B%count -1;
ListNode traverse = A;
while(length > 0)
{
traverse = traverse.next;
length--;
}
A = traverse.next;
traverse.next = null;
return A;
}
}