Given a list, rotate the list to the right by k
places, where k is non-negative.
Example
Given 1->2->3->4->5
and k = 2
, return 4->5->1->2->3
.
SOLUTION:
这题挺有意思的,怎么操作还能rotate呢?很简单,先把链表变成一个环,然后将头节点向后移动k个位置就行了!具体实现的时候,有些还是应该注意的,避免重复的绕圈怎么办?先记录链表的长度,然后k % len一下,就是直翻转一次就OK了。记住,一定返回新的头的位置,不要返回老的头的位置。
代码如下:
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { /** * @param head: the List * @param k: rotate to the right k places * @return: the list after rotation */ public class CurrNode{ ListNode node; CurrNode(ListNode node){ this.node = node; } } public ListNode rotateRight(ListNode head, int k) { if (head == null){ return null; } int len = getLen(head); k = k % len; ListNode preCut = head; ListNode curr = head; while (k > 0){ curr = curr.next; k--; } while (curr.next != null){ curr = curr.next; preCut = preCut.next; } curr.next = head; head = preCut.next; preCut.next = null; //关键,不然就不是合法链表了 return head; } private int getLen(ListNode head){ if (head == null){ return 0; } int len = 0; while (head != null){ head = head.next; len++; } return len; } }
原文:http://www.cnblogs.com/tritritri/p/4971313.html