-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrotate_list.java
More file actions
64 lines (61 loc) · 1.45 KB
/
rotate_list.java
File metadata and controls
64 lines (61 loc) · 1.45 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
public class Solution {
public ListNode rotateRight(ListNode head, int n) {
// Start typing your Java solution below
// DO NOT write main() function
ListNode d=new ListNode(0);
d.next=head;
int i=0;
ListNode n1=head,n2=head;
if(n1==null||n1.next==null) return head;
//n%=len;
while(i++<n) {
n2=n2.next;
if(n2==null) n2=head;
}
while(n2.next!=null) {
n1=n1.next;
n2=n2.next;
}
n2.next=d.next;
d.next=n1.next;
n1.next=null;
return d.next;
}
}
/**
* 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
if(head==null) return null;
int len=0;
ListNode h=head,pre=null,curr=head,p;
while(h!=null) {
len++;
h=h.next;
}
int k=n%len,i=1;
if(k==0) return head;
while(i<len-k+1) {
pre=curr;
curr=curr.next;
i++;
}
pre.next=null;
p=curr;
while(curr.next!=null) curr=curr.next;
curr.next=head;
head=p;
return head;
}
}