Question:
Given a list, rotate the list to the right by k places, where k is non-negative.
For example:
Given1->2->3->4->5->NULL
and k = 2
,return 4->5->1->2->3->NULL
.
Analysis:
给出一个单链表,旋转链表的从右边数k个位置,将他们按顺序放到左边。k是个非负的整数。
注意一些特殊情况:
如当给出的k值比链表长度还大怎么办?当k=0怎么办?
Answer:
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */public class Solution { public ListNode rotateRight(ListNode head, int k) { if(head == null || head.next == null) return head; int len = 0; ListNode p = head; ListNode end = null; while(p != null) { if(p.next == null) end = p; p = p.next; len++; } k %= len; if(k == 0) return head; int pre = len - k; len = 0; p = head; while(len +1 < pre) { p = p.next; len++; } ListNode q = p.next; end.next = head; p.next = null; return q; }}