zoukankan      html  css  js  c++  java
  • 25. K 个一组翻转链表

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

    链表题,这个是基于翻转链表魔改而来,我们可以搭配翻转链表那题来食用。

    题目要求k个一组,我们就是用一个计数器去技术,每当计数器到达k后,就把slow.next置为空,使得它单独成为一个链表,然后把这个链表放入到反转链表的题目的代码中就可以让他翻转了。

    /**
     * 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) {
            int count = 0;
            ListNode dummy = new ListNode(-1);
            ListNode l = dummy;
            dummy.next = head;
            ListNode fast = dummy;
            ListNode slow = null;
            while(fast != null){
                while(fast != null && count < k){
                    count++;
                    fast = fast.next;
                }
                if(count < k || fast == null){
                    break;
                }
                slow = fast;
                fast = fast.next;
                slow.next = null;
                ListNode temp = l.next;
                l.next = helper(l.next);
                temp.next = fast;
                l = temp;
                count = 1;
            }
            return dummy.next;
        }
    
        private ListNode helper(ListNode head){
            ListNode pre = head;
            ListNode cur = head;
            ListNode behind = null;
            while(pre != null){
                pre = pre.next;
                cur.next = behind;
                behind = cur;
                cur = pre;
            }
            return behind;
        }
    }

    我的翻转链表代码使用的是遍历法,前中后三个指针交替交换他们的指向即可。

  • 相关阅读:
    oracle 监听 添加ip
    重装系统windows
    oracle user pwd
    mybatis
    sum行列合计
    IIS8.5 运行WCF
    exp自动备份在bat中不执行
    oem 重建
    yum install oracle-validated
    MSHflexgrid控件删除选中行
  • 原文地址:https://www.cnblogs.com/ZJPaang/p/12899071.html
Copyright © 2011-2022 走看看