-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRotateRight.java
More file actions
106 lines (81 loc) · 1.66 KB
/
Copy pathRotateRight.java
File metadata and controls
106 lines (81 loc) · 1.66 KB
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
import java.util.List;
public class RotateRight {
public static void main(String[] args)
{
ListNode head = new ListNode(1);
head.next = new ListNode(2);
// head.next.next = new ListNode(3);
// head.next.next.next = new ListNode(4);
// head.next.next.next.next = new ListNode(5);
//
// ListNode head = new ListNode(1);
RotateRight r = new RotateRight();
head = r.rotateRight(head, 2);
// print ll
while(head != null)
{
System.out.println(head.val + " ");
head = head.next;
}
}
// template
static class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
next = null;
}
}
public ListNode rotateRight(ListNode head, int n) {
if(head == null)
return head;
if(n == 0)
return head;
if(head.next == null)
return head;
// handle n > size
int size = getSize(head);
n = n % size;
if(n == 0)
return head;
// get the new head
ListNode newHead = nthLast(head,n);
ListNode last = newHead;
//get the last and swing it around
while(last.next != null)
last = last.next;
last.next = head;
//find the new last and mark it
while(head.next != newHead)
{
head = head.next;
}
head.next = null;
return newHead;
}
// get the nth to last
private ListNode nthLast(ListNode head, int n)
{
int size = getSize(head);
ListNode temp = head;
int count = 0;
while(count != size - n)
{
temp = temp.next;
count++;
}
return temp;
}
// size of the linkedlist
private int getSize(ListNode head)
{
int size = 0;
while(head != null)
{
head = head.next;
size++;
}
return size;
}
}