zoukankan      html  css  js  c++  java
  • 25. Reverse Nodes in k-Group (JAVA)

    Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.

    k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of kthen left-out nodes in the end should remain as it is.

    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

    Note:

    • Only constant extra memory is allowed.
    • You may not alter the values in the list's nodes, only nodes itself may be changed.
    /**
     * Definition for singly-linked list.
     * public 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 cur = head;
            ListNode curHead = head; //head of current subgroup
            ListNode nextHead = head; //head of next subgroup
            ListNode preTail = null; //tail of previous subgroup
            while(true){
                //check whether there's enough elements in subgroup
                for(int i = 1; i < k; i++){
                    if(cur == null) break; //not enough element in subgroup
                    cur = cur.next;
                }
                if(cur == null) break; //not enough element in subgroup
                
                //reverse nodes
                cur = curHead.next;
                for(int i = 1; i < k; i++){
                    nextHead = cur.next;
                    if(preTail==null) {
                        cur.next = head;
                        head = cur;
                    }
                    else {
                        cur.next = preTail.next;
                        preTail.next = cur;
                    }
                    cur = nextHead;
                }
                curHead.next = nextHead;
                preTail = curHead;
                curHead = nextHead;
                
            }
            return head;
        }
    }

    因为while语句是无条件循环,特别要注意k==1时的死循环。

  • 相关阅读:
    jdk .tar.gz 包安装 inAction
    Consistent Hashing原理与实现
    开放GitHub的理由
    dll signing issue
    Regular expression cheat sheet
    DOMElement之Offset
    扫码支付测试点
    SQL注入是什么?如何防止?
    什么是接口测试?为什么要做接口测试?如何开展接口测试?
    软件测试的常识
  • 原文地址:https://www.cnblogs.com/qionglouyuyu/p/10775950.html
Copyright © 2011-2022 走看看