https://oj.leetcode.com/problems/rotate-list/
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
.
解题思路:
这题目可以说又是一道很ambiguous的题目。这里的k到底是什么意思,很多人都问了这个问题。下面有个比较清晰的解释。来自以下链接。
https://oj.leetcode.com/discuss/2353/what-to-do-when-k-is-greater-than-size-of-list
Let's start with an example.
Given [0,1,2]
, rotate 1 steps to the right -> [2,0,1]
.
Given [0,1,2]
, rotate 2 steps to the right -> [1,2,0]
.
Given [0,1,2]
, rotate 3 steps to the right -> [0,1,2]
.
Given [0,1,2]
, rotate 4 steps to the right -> [2,0,1]
.
So, no matter how big K, the number of steps is, the result is always the same as rotating K % n
steps to the right.
于是可以看出来,k=k%n,这里n是这个链表里的节点数量。
那么思路就很清楚了,一个快指针,先走k步,然后两个指针一起走,快指针指到结尾停止。再进行指针操作就很清楚了。代码如下。
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { public ListNode rotateRight(ListNode head, int n) { if(head == null || n == 0){ return head; } ListNode headNode = head; ListNode tailNode = head; int size = 1; while(tailNode.next != null){ tailNode = tailNode.next; size++; } n = n % size; if(n == 0){ return head; } tailNode = head; for(int i = 0; i < n && tailNode != null; i++){ tailNode = tailNode.next; } while(tailNode.next != null){ headNode = headNode.next; tailNode = tailNode.next; } ListNode returNode = headNode.next; tailNode.next = head; headNode.next = null; return returNode; } }