标签:
原题链接在这里:https://leetcode.com/problems/rotate-list/
向右rotate k 个点,就是从list 倒数k个点 然后断开把后部加在头上就好。
先求整个长度len, 如果k长于len, 那么k = k%len, 此时判断若是k == 0, 则不用rotate.
否则从头走len-k步,然后断开,后半部的加到前面来。
Note: 注意k 取模后若是k == 0, 需要返回,这是一个corner case 否则后面的 temp.next 就会报错,因为k == 0后,temp已经走到了null的位置上。
找到list倒数几个点时还可以用快慢双指针的方法,快的指针先走k步。
AC Java:
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 || k == 0){ 12 return head; 13 } 14 //Calculate the length of the list 15 int len = 0; 16 ListNode current = head; 17 while(current != null){ 18 current = current.next; 19 len++; 20 } 21 //if k is larger than the length, k = k%len 22 if(k>=len){ 23 k = k%len; 24 } 25 //if k is 0, no need to rotate, also the corner case 26 if(k == 0){ 27 return head; 28 } 29 30 int count = len - k; 31 ListNode dummy = new ListNode(0); 32 dummy.next = head; 33 current = dummy; 34 while(count > 0){ 35 current = current.next; 36 count--; 37 } 38 ListNode temp = current.next; 39 current.next = null; 40 dummy.next = temp; 41 //Pay attention on the corner case when temp == null 42 while(temp.next != null){ 43 temp = temp.next; 44 } 45 temp.next = head; 46 return dummy.next; 47 } 48 }
标签:
原文地址:http://www.cnblogs.com/Dylan-Java-NYC/p/4876904.html