leetcode解题方案--061--RotateList

来源:互联网 发布:linux菜鸟私房菜 编辑:程序博客网 时间:2024/06/01 09:40

题目

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个链表节点。
两个指针同时移动。然后。。。。
没什么难度。
让人觉得难过的点是,这个k可能大于数组长度,因此我先求了数组长度,然后取余。
还有一种思路是把首尾连起来 组成一个环,思路大致相同。如果k依然大于零而已经到末尾,则从头开始,继续循环。

public static ListNode rotateRight(ListNode head, int k) {        if (head == null) {            return null;        }        ListNode last = head;        int length = 0;        while (last != null) {            length++;            last = last.next;        }        k = k % length;        last = head;        ListNode lastk = head;        while (k-- > 0) {            last = last.next;        }        if (last == null) {            return head;        }        while (last.next != null) {            last = last.next;            lastk = lastk.next;        }        last.next = head;        ListNode ret = lastk.next;        lastk.next = null;        return ret;    }
原创粉丝点击