forked from hongtaocai/code_interview
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrotatelist.java
More file actions
executable file
·41 lines (41 loc) · 899 Bytes
/
rotatelist.java
File metadata and controls
executable file
·41 lines (41 loc) · 899 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
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode rotateRight(ListNode head, int n) {
// Start typing your Java solution below
// DO NOT write main() function
int length = 0;
ListNode p = head;
ListNode tail = head;
while(p!=null){
length++;
tail = p;
p = p.next;
}
if(length==0){
return head;
}
n = n%length;
if(n==0) return head;
n = length-n;
n = n-1;
p = head;
while(n>0){
p = p.next;
n--;
}
ListNode newhead = p.next;
tail.next = head;
p.next = null;
return newhead;
}
}