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
.
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { val = x; } 7 * } 8 */ 9 public class Solution { 10 public ListNode rotateRight(ListNode head, int k) { 11 if (head == null || head.next == null) { 12 return head; 13 } 14 ListNode dummy = new ListNode(0); 15 dummy.next = head; 16 ListNode node = dummy; 17 int len = 0; 18 ListNode tail; 19 while (node.next != null) { 20 len++; 21 node = node.next; 22 } 23 //System.out.println(len); 24 tail = node; 25 k = k % len; 26 if (k == 0) { 27 return dummy.next; 28 } 29 node = dummy; 30 for (int i = 0; i < len - k; i++) { 31 node = node.next; 32 } 33 tail.next = dummy.next; 34 dummy.next = node.next; 35 node.next = null; 36 return dummy.next; 37 } 38 }
时间: 2024-12-17 19:54:55