美文网首页
LeetCode 61. Rotate List

LeetCode 61. Rotate List

作者: 关玮琳linSir | 来源:发表于2017-10-26 21:21 被阅读18次

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

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

    题意:旋转链表,k是旋转几位。

    思路:对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 cnt = 1;
            ListNode p2 = head;
            while (p2.next != null) {
                cnt++;
                p2 = p2.next;
            }
            k = k % cnt;
            ListNode pHead = head;
            ListNode p1 = head;
            for (int i = 0; i < cnt - k - 1; i++) {
                p1 = p1.next;
            }
            p2.next = pHead;
            pHead = p1.next;
            p1.next = null;
            return pHead;
        }
    }
    

    相关文章

      网友评论

          本文标题:LeetCode 61. Rotate List

          本文链接:https://www.haomeiwen.com/subject/sbklpxtx.html