zoukankan      html  css  js  c++  java
  • reverse-nodes-in-k-group

    https://leetcode.com/problems/reverse-nodes-in-k-group/

    https://leetcode.com/mockinterview/session/result/xjlzcwc/

    链表分批倒置,还是有点绕的。用了三个临时变量来处理。需要细心,也需要掌握类似经验。

    package com.company;
    
    
    import java.util.*;
    
    class ListNode {
        int val;
        ListNode next;
        ListNode(int x) { val = x; }
    }
    
    class Solution {
        public ListNode reverseKGroup(ListNode head, int k) {
            if (k <= 1) {
                return head;
            }
    
            ListNode ret = new ListNode(0);
            ret.next = head;
    
            ListNode cur = ret;
            ListNode next = head;
            ListNode first = null;
            ListNode second = null;
            ListNode third = null;
            while (true) {
                int i=0;
                for (; i<k; i++) {
                    if (next == null) {
                        break;
                    }
                    next = next.next;
                }
                if (i < k) {
                    break;
                }
    
                first = cur.next;
                second = first.next;
                for (i=0; i<k-1; i++) {
                    third = second.next;
                    second.next = first;
                    first = second;
                    second = third;
                }
                cur.next.next = next;
                third = cur.next;
                cur.next = first;
                cur = third;
            }
    
            return ret.next;
        }
    }
    
    public class Main {
    
        public static void main(String[] args) throws InterruptedException {
    
            System.out.println("Hello!");
            Solution solution = new Solution();
    
            // Your Codec object will be instantiated and called as such:
            ListNode ln1 = new ListNode(1);
            ListNode ln2 = new ListNode(2);
            ListNode ln3 = new ListNode(3);
            ListNode ln4 = new ListNode(4);
            ListNode ln5 = new ListNode(5);
            ln1.next = ln2;
            ln2.next = ln3;
            ln3.next = ln4;
            ln4.next = ln5;
    
            ListNode ret = solution.reverseKGroup(ln1, 3);
            for (int i=0; i<5; i++) {
                System.out.printf("ret:%d
    ", ret.val);
                ret = ret.next;
            }
    
            System.out.println();
    
        }
    
    }
  • 相关阅读:

    CreateProcess
    luogu P2234 [HNOI2002]营业额统计 |平衡树
    luogu P2286 [HNOI2004]宠物收养场 |平衡树
    luogu P3369 【模板】普通平衡树
    luogu P3834 【模板】可持久化线段树 1(主席树)| 静态第k小问题
    luogu P4149 [IOI2011]Race |点分治
    luogu P2634 [国家集训队]聪聪可可 |点分治
    luogu P4178 Tree |点分治+树状数组
    luogu P2664 树上游戏 |点分治
  • 原文地址:https://www.cnblogs.com/charlesblc/p/6033738.html
Copyright © 2011-2022 走看看