forked from yuyongwei/Algorithms-In-Swift
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathrotateList.java
More file actions
43 lines (35 loc) · 791 Bytes
/
rotateList.java
File metadata and controls
43 lines (35 loc) · 791 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
/*
Given a linked list, rotate the list to the right by k places, where k is non-negative.
https://leetcode.com/problems/rotate-list/
*/
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode rotateRight(ListNode head, int k) {
if (head == null || k <= 0) return head;
int length = 1;
ListNode curr = head;
while (curr.next != null) {
curr = curr.next;
length += 1;
}
//connect tail to head
curr.next = head;
//find the left place
int p = length - k % length;
//find the palce
for (int i = 0; i < p; i++) {
curr = curr.next;
}
//break the list
head = curr.next;
curr.next = null;
return head;
}
}