zoukankan      html  css  js  c++  java
  • [Leetcode] Reverse Nodes in k-Group

    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 left-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

    Solution:

    1. 先遍历一边list找到有几个要reverse的group。

    2. group内部的reverse总共只用3个pointer:pre, cur, move的方法!

    注意:  ListNode的reverse还需要再练习

     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         if(head==null)
    15             return head;
    16         int reverseTimes=getLength(head)/k;
    17         ListNode dummy=new ListNode(-1);
    18         dummy.next=head;
    19         ListNode pre=dummy;
    20         ListNode cur=dummy.next;
    21         while(reverseTimes!=0){
    22             reverseTimes--;
    23             for(int i=0;i<k-1;++i){
    24                 ListNode move=cur.next;
    25                 cur.next=move.next;
    26                 move.next=pre.next;
    27                 pre.next=move;
    28             }
    29             pre=cur;
    30             cur=cur.next;
    31         }
    32         return dummy.next;
    33     }
    34 
    35     private int getLength(ListNode head) {
    36         // TODO Auto-generated method stub
    37         ListNode cur=head;
    38         int cnt=0;
    39         while(cur!=null){
    40             cnt++;
    41             cur=cur.next;
    42         }
    43         return cnt;
    44     }
    45 }
  • 相关阅读:
    数据结构 trie 树 入门练手 POJ 3630 Phone List
    回溯法求 1~n 的排列
    POJ 1988 Cube Stacking (并查集,节点到根节点的距离题目)
    Ubuntu下的截图软件
    git使用方法
    在Linux下安装ADT
    在Linux下安装Android SDK
    在Linux下安装Java JDK
    研发项目风险因素差异性
    关于C#的partial修饰符
  • 原文地址:https://www.cnblogs.com/Phoebe815/p/4104801.html
Copyright © 2011-2022 走看看