Given a list, rotate the list to the right by k places, where k is non-negative.
Example:
Given 1->2->3->4->5->NULL and k = 2, return 4->5->1->2->3->NULL.
package leetCode; /** * Created by lxw, liwei4939@126.com on 2018/3/10. */ class ListNode{ int val; ListNode next; ListNode(int x){ val = x; } } public class L061_Rotate_List { public ListNode rotateRight(ListNode head, int k){ if (head == null || head.next == null){ return head; } int len = 1; ListNode tail = head; while (tail.next != null){ len ++; tail = tail.next; } tail.next = head; k %= len; for (int i = 1; i < len - k; i ++){ head = head.next; } try { return head.next; } finally { head.next = null; } } public static void main(String[] args){ L061_Rotate_List tmp = new L061_Rotate_List(); ListNode head = new ListNode(1); ListNode tmpNode = head; for (int i =2; i <= 5; i++){ ListNode cur = new ListNode(i); tmpNode.next = cur; tmpNode = cur; } tmpNode.next = null; head = tmp.rotateRight(head, 2); while (head != null){ System.out.print(head.val + "->"); head = head.next; } System.out.print("NULL."); } }
本文介绍了一个算法问题:如何将链表向右旋转k个位置。通过一个具体的例子展示了旋转链表的具体实现方法,并提供了一段Java代码实现。该算法首先计算链表长度,然后将链表尾部连接到头部形成环形链表,最后断开指定位置完成旋转。

1616

被折叠的 条评论
为什么被折叠?



