首页 > 代码库 > [leetcode] Rotate List

[leetcode] Rotate List

Given a list, rotate the list to the right by k places, where k is non-negative.

For example:
Given1->2->3->4->5->NULLand k =2,
return4->5->1->2->3->NULL.

https://oj.leetcode.com/problems/rotate-list/

思路1:先遍历一遍求长度,然后从头再开始走k%len步,设置新的头尾节点,连接原来的头尾节点。

思路2:遍历求长度,将首尾连接,继续走到新的头尾,断开。

 

思路1代码:

public class Solution {    public ListNode rotateRight(ListNode head, int n) {        if (head == null)            return null;        int len = 0;        ListNode p = head;        while (p != null) {            len++;            p = p.next;        }                p = head;        int i;        n = n % len;        if (n == 0)            return head;        for (i = 0; i < len - n - 1; i++)            p = p.next;        ListNode newTail = p;        ListNode newHead = p.next;        while (p.next != null)            p = p.next;        p.next = head;        newTail.next = null;        return newHead;    }    public static void main(String[] args) {        ListNode head = ListUtils.makeList(1, 2, 3, 4, 5);        ListUtils.printList(head);        head = new Solution().rotateRight(head, 2);        ListUtils.printList(head);    }}