-
Notifications
You must be signed in to change notification settings - Fork 2
/
RotateList.java
56 lines (51 loc) · 1.45 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
package src.java.medium.linkedlist;
/**
* Definition for singly-linked list. public class ListNode { int val; ListNode
* next; ListNode(int x) { val = x; next = null; } }
*/
public class RotateList {
public ListNode rotateRight2(ListNode head, int k) {
if (head == null || k == 0) return head;
int count = 0;
ListNode cur = head;
while(cur != null) {
cur = cur.next;
count++;
}
k = count - k%count;
ListNode pre = null;
cur = head;
while(k > 0) {
k--;
pre = cur;
cur = cur.next;
}
pre.next = null;
if (cur==null) return head;
ListNode newHead = cur;
while(cur.next != null) cur = cur.next;
cur.next = head;
return newHead;
}
public ListNode rotateRight(ListNode head, int n) {
// Start typing your Java solution below
// DO NOT write main() function
if (head==null || n==0) return head;
ListNode first = head;
while(n>0){
if(first==null) first=head;
first = first.next;
n--;
}
if(first==null) return head;
ListNode second = head;
while(first.next!=null){
second = second.next;
first = first.next;
}
first.next = head;
ListNode ret = second.next;
second.next = null;
return ret;
}
}