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

    k个元素一组指针反转

    函数调用问题!!!!

     1 /**
     2  * Definition for singly-linked list.
     3  * public class ListNode {
     4  *     int val;
     5  *     ListNode next;
     6  *     ListNode(int x) {
     7  *         val = x;
     8  *         next = null;
     9  *     }
    10  * }
    11  */
    12 public class Solution {
    13     public ListNode reverseKGroup(ListNode head, int k) {
    14         // Start typing your Java solution below
    15         // DO NOT write main() function
    16         
    17         if(head == null || k == 1)
    18             return head;
    19             
    20         int len = 0;
    21         ListNode p = head;
    22         while(p != null){
    23             p = p.next;
    24             len ++;
    25         }
    26         
    27         ListNode safeG = new ListNode(-1);
    28         safeG.next = head;
    29         ListNode pre = safeG, cur = head, post = head.next;
    30         
    31         int m = len / k;
    32         for(int i = 0; i < m; i++){
    33             post = cur.next;
    34             //reverse(pre, cur, post, k);
    35             int j = 0;            
    36             while(post != null){
    37                 ListNode tmp = post.next;
    38                 post.next = cur;
    39                 cur = post;
    40                 post = tmp;
    41                 j ++;
    42                 if(j == k - 1)
    43                     break;
    44             }
    45             ListNode tmp = pre.next;
    46             pre.next = cur;
    47             tmp.next = post;
    48             pre = tmp;
    49             cur = pre.next;
    50             
    51         }
    52         
    53         return safeG.next;
    54         
    55     }
    56     
    57     public void reverse(ListNode pre, ListNode cur, ListNode post, int k){
    58         int i = 0;            
    59         while(post != null){
    60             ListNode tmp = post.next;
    61             post.next = cur;
    62             cur = post;
    63             post = tmp;
    64             i ++;
    65             if(i == k - 1)
    66                 break;
    67         }
    68     }
    69     
    70 }
  • 相关阅读:
    SpringMVC中的适配器
    JVM的理解
    设计模式 特点比较
    AOP代理模式
    Spring配置补充
    MayBatis与Spring的整合
    增强和注解
    注入
    Mybatis的执行过程
    k8s认证与授权
  • 原文地址:https://www.cnblogs.com/feiling/p/3201464.html
Copyright © 2011-2022 走看看