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;
    }
    }
    }
    }

  • 相关阅读:
    今发现“最全前端资源汇集”,果断收藏
    js基础
    重排版与重绘
    小乌龟的配置
    考试网站
    苹果手机上时间的兼容
    自定义alert
    [概率dp] 流浪地球
    [权值线段树] 1163B2 Cat Party (Hard Edition)
    [单调栈]1156E Special Segments of Permutation
  • 原文地址:https://www.cnblogs.com/huaiyinxiaojiang/p/6425845.html
Copyright © 2011-2022 走看看