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

    Have you met this question in a real interview?
     
    Analysis:
    Scan the whole list and find out the length len, then calculate the number of reverse iterations, which is len/k. For each iteration, reverse the corresponding group of nodes.
     
    Solution:
     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 || head.next==null) return head;
    15         if (k==0 || k==1) return head;
    16 
    17         ListNode preHead = new ListNode(0);
    18         preHead.next = head;
    19         ListNode cur = head;
    20         int len = 1;
    21         while (cur.next!=null){
    22             cur = cur.next;
    23             len++;
    24         }
    25 
    26         int iterNum = len/k;
    27         ListNode start = preHead;
    28         cur = head;
    29         for (int i=0;i<iterNum;i++){
    30             for (int j=0;j<k-1;j++){
    31                 ListNode temp = cur.next.next;
    32                 cur.next.next = start.next;
    33                 start.next = cur.next;
    34                 cur.next = temp;
    35             }
    36 
    37             start = cur;
    38             cur = cur.next;
    39         }
    40 
    41         return preHead.next;
    42     }
    43 }

    NOTE: Without counting the length of the list first,  we can also count whether there are k number of nodes left in the rest of list at the begnning of every reverse iteration.

  • 相关阅读:
    六:页面优化
    五:title,keywords,description标签
    专题之一:开篇有益
    通过JavaScript以及ActiveX控件获得客户端的机器名[Z]
    [1]Web Service简介
    (转载)虚拟环境中的隐蔽信道(续)
    虚拟机VMware如何能将屏幕调大
    VMware下Ubuntu上网设置
    基于CPU负载的隐蔽信道 ——> ——>基于网络负载的隐蔽信道
    Ubuntu 12.04终端Terminal快捷方式调用
  • 原文地址:https://www.cnblogs.com/lishiblog/p/4114632.html
Copyright © 2011-2022 走看看