Leetcode 61. Rotate List
2017-04-24 21:57
260 查看
// Given a list, rotate the list to the right by k places, where k is // non-negative. // // For example: // Given 1->2->3->4->5->NULL and k = 2, // return 4->5->1->2->3->NULL. public class Main { public static void main(String[] args) throws Exception { ListNode node1 = new ListNode(); ListNode node2 = new ListNode(); ListNode node3 = new ListNode(); ListNode node4 = new ListNode(); ListNode node5 = new ListNode(); node1.data = 1; node2.data = 2; node3.data = 3; // node4.data = 4; // node5.data = 5; node1.next = node2; node2.next = node3; // node3.next = node4; // node4.next = node5; rotateRight(node1, 1); while (node1 != null) { System.out.println(node1.data); node1 = node1.next; } } public static ListNode rotateRight(ListNode head, int k) { if (head == null) { return null; } if (head.next == null) { return head; } if (k == 0) { return head; } int length = 0; ListNode point = head; while (point != null) { length++; point = point.next; } int move = 0; if(k>length){ move = k%length; }else{ move = k; } if(move == 0){ return head; } ListNode result = head; int temp = 0; while (temp != move) { result = result.next; temp++; } ListNode node = head; if(result == null){ return head; } while (result.next != null) { result = result.next; node = node.next; } ListNode r = node.next; node.next = null; result.next = head; return r; } }
相关文章推荐
- leetcode 61. Rotate List
- LeetCode 61. Rotate List
- 【leetcode】61. Rotate List
- Leetcode 61. Rotate List
- LeetCode61 Rotate List
- (Java)LeetCode-61. Rotate List
- leetcode - 61.Rotate List
- [LeetCode61]Rotate List
- [leetcode]61. Rotate List
- Leetcode 61. Rotate List
- [Leetcode]@python 61. Rotate List
- LeetCode 61. Rotate List
- leetcode61: Rotate List
- [LeetCode] 61. Rotate List
- LeetCode 61 Rotate List
- LeetCode 61. Rotate List
- LeetCode 61. Rotate List
- leetcode 61.Rotate List
- LeetCode----- 61. Rotate List
- Leetcode 61. Rotate List