TypechoJoeTheme

IT技术分享

统计

[LeetCode 61] Rotate List [Java]

2018-02-04
/
0 评论
/
694 阅读
/
正在检测是否收录...
02/04

1. Description

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

2. Example

Given 1->2->3->4->5->NULL and k = 2,
return 4->5->1->2->3->NULL.

3. Code

public class LeetCode0061 {

    class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
        }
    }

    public ListNode rotateRight(ListNode head, int k) {

        if (head == null || head.next == null || k == 0) {
            return head;
        }

        ListNode p = head;
        int n = 1;

        for (; p.next != null; n++) {
            p = p.next;
        }

        ListNode lastNode = p;

        k %= n;
        if (k == 0) {
            return head;
        }

        k = n - k;
        ListNode q = head;
        p = head.next;

        for (int i = 1; p != null && i < k; i++) {
            q = p;
            p = p.next;
        }

        q.next = null;
        lastNode.next = head;
        return p;
    }
}
Linked
朗读
赞 · 0
版权属于:

IT技术分享

本文链接:

https://idunso.com/archives/1423/(转载时请注明本文出处及文章链接)