• K组翻转链表 · Reverse Nodes in k-Group


    [抄题]:

    给你一个链表以及一个k,将这个链表从头指针开始每k个翻转一下。
    链表元素个数不是k的倍数,最后剩余的不用翻转。

    [思维问题]:

    [一句话思路]:

    // reverse head->n1->..->nk->next.. // to head->nk->..->n1->next.. // return n1 每k个转一次,再递归

    [输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

    [画图]:

    [一刷]:

    1. head = dummy,记住:head从第0位开始
    2. if (head == null || k <= 1) {
      return head; k == 1时,返回原来的head不转就行,不是返回null
      }

    3. head.next要新存节点,否则会报错,递归还不能debug
    4. reverseNextK是需要循环调用的,是否够k个数的判断在其中完成。
    5. n1.next = curt;指针先连接
      head.next = prev;本体后连接,防止破坏指针

    6. next.next为空时退出,特殊情况应该是退出

    [总结]:

    head = dummy,记住:从第0位开始

    [复杂度]:Time complexity: O(n) Space complexity: O(1)

    [英文数据结构,为什么不用别的数据结构]:

    [其他解法]:

    [Follow Up]:

    [题目变变变]:

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    
    
    public class Solution {
        /*
         * @param head: a ListNode
         * @param k: An integer
         * @return: a ListNode
         */
        public ListNode reverseKGroup(ListNode head, int k) {
            if (head == null || k <= 1) {
                return head;
            }
            ListNode dummy = new ListNode(0);
            dummy.next = head;
            head = dummy;
            
            while (head.next != null) {
                head = reverseNextK(head,k);
            }
            
            return dummy.next;
        }
        
        //reverseNextK
        private ListNode reverseNextK(ListNode head, int k) {
            ListNode next = head;
            for (int i = 0; i < k; i++) {
                if (next.next == null) {
                    return next;
                }
                next = next.next;
            }//whether next is enough
            
            ListNode prev = head;
            ListNode n1 = head.next;
            ListNode curt = n1;
            for (int i = 0; i < k; i++) {
                ListNode temp = curt.next;
                curt.next = prev;
                prev = curt;
                curt = temp;
            }
            
            n1.next = curt;
            head.next = prev;
            
            return n1;
        }
    }
    View Code
  • 相关阅读:
    iOS设备后台播放音乐方法
    iOS 编译64位FFMPEG
    os8 location authorization 错误.
    IOS 使用新浪微博SDK
    IOS 解析歌词lrc
    IOS 通过button获取cell
    IOS 解析XML文档
    OC .(点)与->(箭头)用法区别
    黑苹果安装合集
    Hello,World
  • 原文地址:https://www.cnblogs.com/immiao0319/p/8215560.html
Copyright © 2020-2023  润新知