zoukankan      html  css  js  c++  java
  • Leetcode: 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.

    Anaylisis: Linked List题目的做法其实比较固定,就是Runner Technique(Two pointer) 方法加上 Dummy Node(设置一个head之前的虚假节点)两种方法,这道题就这样搞一搞就出来了。

    需要注意的是:处理null 输入需要特别考虑,然后,需要找到新的linked list的头

    第二遍做法:注意15行需要特别处理,wrap up了之后n=0的情况

     1 public class Solution {
     2     public ListNode rotateRight(ListNode head, int n) {
     3         if (head == null) return null;
     4         ListNode dummy = new ListNode(-1);
     5         dummy.next = head;
     6         ListNode cursor = dummy;
     7         ListNode walker = dummy;
     8         ListNode runner = dummy;
     9         int count = 0;
    10         while (cursor.next != null) {
    11             cursor = cursor.next;
    12             count ++;
    13         }
    14         n %= count;
    15         if (n == 0) return head;
    16         while (n > 0) {
    17             runner = runner.next;
    18             n--;
    19         }
    20         while (runner.next != null) {
    21             runner = runner.next;
    22             walker = walker.next;
    23         }
    24         dummy.next = walker.next;
    25         walker.next = runner.next;
    26         runner.next = head;
    27         return dummy.next;
    28     }
    29 }
  • 相关阅读:
    java内存管理之内存模型
    HTTP协议
    12 数值的整数次方
    11 二进制中1的个数+二进制补充知识点
    10 矩形覆盖
    9 变态跳台阶
    8 跳台阶
    7斐波那契数列
    6旋转数组的最小数字
    5用两个栈实现队列
  • 原文地址:https://www.cnblogs.com/EdwardLiu/p/3805191.html
Copyright © 2011-2022 走看看