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
.node
向右旋转一个单链表,旋转k个位置,k非负数。算法
用一个辅助root结点链接到链表头,先找到要移动的第一个结点的前驱prev,再将prev后的全部结点接到root后面,再将组成一个旋转后的单链表。spa
链表结点类.net
public class ListNode { int val; ListNode next; ListNode(int x) { val = x; } }
算法实现类code
public class Solution { public ListNode rotateRight(ListNode head, int n) { if (head == null || n < 1) { return head; } ListNode root = new ListNode(0); root.next = head; ListNode p = root; ListNode q = root; int count = 0; for (int i = 0; i <=n; i++) { p = p.next; count++; if (p == null) { count--; // 链表中除头结点后数据个数 n = n % count; // 实际要位置的位数 // 为从新开始位移作准备 i = 0; p = head; } } // 找到第一个要交换的结点的前驱 // q为第一个要交换的结点的前驱 while (p != null) { p = p.next; q = q.next; } p = q; q = root; if (p != null && p.next != null) { // 有要位移的结点 ListNode node; while (p.next != null) { // 摘除结点 node = p.next; p.next = node.next; // 接上结点 node.next = q.next; q.next = node; q = node; // 最后一个移动的节点 } } return root.next; } }