原创

[百战LeetCode][6.链表中元素每K个元素反转]


==========================努力奋斗财源广进==========================

一、算法题目

将给出的链表中的节点每 k 个一组翻转,返回翻转后的链表 如果链表中的节点数不是 k 的倍数,将最后剩下的节点保持原样 你不能更改节点中的值,只能更改节点本身。

二、题解

1、我的题解

public ListNode reverseKGroup (ListNode head, int k) {
        // write code here
        //找到每次翻转的尾部
        ListNode tail = head;
        //遍历k次到尾部
        for(int i = 0; i < k; i++){
            if(tail == null) return head;
            tail = tail.next;
        }
        ListNode pre = null;
        ListNode cur = head;
        while(cur != tail){
            ListNode tem = cur.next;
            cur.next = pre;
            pre = cur;
            cur = tem;
        }
        head.next = reverseKGroup(tail, k);
        return pre;
    }

2、优秀题解

import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 * }
 */

public class Solution {
    /**
     * 
     * @param head ListNode类 
     * @param k int整型 
     * @return ListNode类
     */
    public ListNode reverseKGroup (ListNode head, int k) {
        if (head == null || head.next == null) {
            return head;
        }
        
        ListNode tail = head;
        
        for (int i = 0; i < k; ++i) {
            if (tail == null) {
                return head;
            }
            tail = tail.next;
        }
        
        ListNode newHead = reverse(head, tail);
        
        head.next = reverseKGroup(tail, k);
        
        return newHead;
    }
    
    ListNode reverse(ListNode node, ListNode end) {
        if (node.next == end) {
            return node;
        }
        
        ListNode next = node.next;
        ListNode reverse = reverse(next, end);
        
        next.next = node;
        node.next = null;
        
        return reverse;
    }
}

复习的时候新增的一套解法,和题解1类似只不过是改动了一些。

import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 * }
 */

public class Solution {
    /**
     * 
     * @param head ListNode类 
     * @param k int整型 
     * @return ListNode类
     */
    public ListNode reverseKGroup (ListNode head, int k) {
        // write code here
        ListNode tail = head;
        for(int i = 0; i < k; i++){
            if(tail == null) return head;
            tail = tail.next;
        }
        ListNode dummy = new ListNode(-1);
        dummy.next = head;
        ListNode cur = head;
        ListNode curNext = null;
        for(int i = 0; i < k - 1; i++){
            curNext = cur.next;
            cur.next = curNext.next;
            curNext.next = dummy.next;
            dummy.next = curNext;
        }
        head.next = reverseKGroup(tail, k);
        return dummy.next;
    }
}

三、解法心得

四、自我监督

评论区记录复习记录

  • 作者:北斗七点半联系作者
  • 发表时间:2022-07-17 20:50
  • 版权声明:禁止转载
  • 非公众号转发
  • 评论