zoukankan      html  css  js  c++  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 left-out nodes in the end should remain as it is.

    我用String代替了链表显示,本题的大意是每k个进行逆序处理,剩下的不够k个的就按照原顺序保留下来。

    public class ReverseNodes {
    public static void main(String[] args) {
    String str = "1->2->3->4->5->6->7->8->9->10->11->12->13->14->15";
    String[] strArray = str.split("->");
    int k = 2;
    /**
    * int k = 2; 2->1->4->3->6->5->8->7->10->9->12->11->14->13->15
    * int k = 4; 4->3->2->1->8->7->6->5->12->11->10->9->13->14->15
    * int k = 3; 3->2->1->6->5->4->9->8->7->12->11->10->15->14->13
    */
    String[] results = reveseNodes(k,strArray);
    for(int i = 0; i < results.length; ++i){
    if(i == strArray.length - 1){
    System.out.print(results[i]);
    }else{
    System.out.print(results[i] + "->");
    }
    }
    }
    public static String[] reveseNodes(int k, String[] strArray) {
    int left = strArray.length % k;
    int start = 0;
    if(strArray.length / k == 0){
    return strArray;
    }
    while(start < strArray.length - left){
    DiedaiReverse(start,k,strArray);
    start += k;
    }
    return strArray;
    }
    public static void DiedaiReverse(int start, int k, String[] strArray) {
    int j = 0;
    if(k%2 == 0){
    for(int i = start; i < (start + start + k)/2; ++i){
    String temp = strArray[i];
    strArray[i] = strArray[start+k-1-j];
    strArray[start+k-1-j] = temp;
    ++j;
    }
    }else{
    for(int i = start; i <= (start + start + k)/2; ++i){
    String temp = strArray[i];
    strArray[i] = strArray[start+k-1-j];
    strArray[start+k-1-j] = temp;
    ++j;
    }
    }
    }
    }

  • 相关阅读:
    勘测定界三调版发布
    混沌加密解密,附带完整C#源码
    c# 获取照片的经纬度和时间
    第8章代码
    使用Python读取照片的GPS信息
    6章代码
    python运行时间的两种方法
    5章代码
    在 ArcGIS 中使用的查询表达式的 SQL 参考
    15章代码
  • 原文地址:https://www.cnblogs.com/huaiyinxiaojiang/p/6425845.html
Copyright © 2011-2022 走看看