zoukankan      html  css  js  c++  java
  • Reverse Nodes in k-Group LeetCode Java

    描述
    Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
    If the number of nodes is not a multiple of k then le�-out nodes in the end should remain as it is.
    You may not alter the values in the nodes, only nodes itself may be changed.
    Only constant memory is allowed.
    For example, Given this linked list: 1->2->3->4->5
    For k = 2, you should return: 2->1->4->3->5
    For k = 3, you should return: 3->2->1->4->5

    分析

    给定链表,一次反转链表k的节点并返回其修改的列表。
    如果节点的数目不是k的倍数,那么最终的节点应该保持原样。
    可能不会更改节点中的值,而只能更改节点本身。

    例如,给定这个链表:1>2>3>4>5。
    对于k=2,你应该返回:2 ->1 ->4>3>5。
    对于k=3,你应该返回:3 ->2 ->1>4>5。

    注意越界问题,

    代码

     1 public static ListNode reverseNodeInKGrop(ListNode head, int n) {
     2         if (head == null || head.next == null || n == 1)
     3             return head;
     4         ListNode fakehead = new ListNode(-1);
     5         fakehead.next = head;
     6         ListNode ptr1 = head, ptr2 = fakehead.next.next, newstart = fakehead;
     7         int len = 0;
     8         while (ptr1 != null) {
     9             len++;
    10             ptr1 = ptr1.next;
    11         }
    12         ptr1 = fakehead.next;
    13         if(n!=len)
    14            n = n % len;
    15         int k = len / n;
    16         for (int j = 0; j < k; j++) {
    17 
    18             for (int i = 1; i < n; i++) {
    19                 ptr1.next = ptr2.next;
    20                 ptr2.next = newstart.next;
    21                 newstart.next = ptr2;
    22                 ptr2 = ptr1.next;
    23             }
    24             
    25             for (int i = 0; i < n; i++) {
    26                 newstart = newstart.next;
    27             }
    28 
    29             if (ptr2 != null && ptr2.next != null) {
    30                 ptr1 = newstart.next;
    31                 ptr2 = ptr1.next;
    32             }
    33         }
    34 
    35         return fakehead.next;
    36     }
  • 相关阅读:
    Java Synchronized的用法
    静态方法中不能new内部类的实体对象
    android ViewGroup事件分发机制
    安卓设备通过USB接口读取UVC摄像头权限问题
    android View事件分发机制结论
    函数指针与指针函数以及typedef
    GeoHash
    快速排序,C语言实现
    字符串的几个算法
    ANSI C与GNU C
  • 原文地址:https://www.cnblogs.com/ncznx/p/9160648.html
Copyright © 2011-2022 走看看