61. Rotate List
来源:互联网 发布:sem广告投放优化师 编辑:程序博客网 时间:2024/06/05 19:13
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.
思路:
把链表连成环,再在特定的位置断开。注意k可能大于链表的长度。
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */class Solution { public ListNode rotateRight(ListNode head, int k) { if (head == null || k == 0) { return head; } int length = 1; ListNode node = head; while (node.next != null) { ++length; node = node.next; } node.next = head; int m = k % length; for (int i = 0; i < length - m; ++i) { node = node.next; } head = node.next; node.next = null; return head; }}
阅读全文