zoukankan      html  css  js  c++  java
  • LeetCode 61. Rotate List

    原题链接在这里:https://leetcode.com/problems/rotate-list/

    题目:

    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.

    题解:

    快慢指针, 先算长度len, runner停在tail node.

    walker移动 len- k%len 步数后断开后面, runner.next指向head.

    Time Complexity: O(n). Space: O(1).

    AC Java:

     1 /**
     2  * Definition for singly-linked list.
     3  * public class ListNode {
     4  *     int val;
     5  *     ListNode next;
     6  *     ListNode(int x) { val = x; }
     7  * }
     8  */
     9 public class Solution {
    10     public ListNode rotateRight(ListNode head, int k) {
    11         if(head == null || head.next == null){
    12             return head;
    13         }
    14         
    15         ListNode dummy = new ListNode(0);
    16         dummy.next = head;
    17         ListNode walker = dummy;
    18         ListNode runner = dummy;
    19         
    20         int len = 0;
    21         while(runner.next != null){
    22             runner = runner.next;
    23             len++;
    24         }
    25         
    26         int jump = len-(k%len);
    27         while(jump -- > 0){
    28             walker = walker.next;
    29         }
    30         
    31         runner.next = dummy.next;
    32         dummy.next = walker.next;
    33         walker.next = null;
    34         
    35         return dummy.next;
    36     }
    37 }

    Rotate Array相似

  • 相关阅读:
    《将博客搬至CSDN》
    选课系统
    ATM_购物车
    python基础 面向对象编程
    python 基础 模块
    python基础 函数基础 模块:总复习
    第三篇:操作系统基础
    浅谈红黑树
    浅谈B和B+树
    第二篇:网络基础
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/4876904.html
Copyright © 2011-2022 走看看