/**

  • 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 (head == null || k == 1) { return head; } ListNode dummy = new ListNode(0); dummy.next = head; ListNode pre = dummy; ListNode end = dummy; while (end.next != null) { for (int i = 0; i < k && end != null; i++) { end = end.next; } if (end == null) { break; } ListNode start = pre.next; ListNode next = end.next; end.next = null; pre.next = reverse(start); start.next = next; pre = start; end = start; } return dummy.next; }

    private ListNode reverse(ListNode head) { ListNode pre = null; ListNode cur = head; while (cur != null) { ListNode next = cur.next; cur.next = pre; pre = cur; cur = next; } return pre; } }

给出的链表中的节点每K个一组翻转返回翻转后的链表如果链表中的节点不是k的倍数将最后剩下的节点保持原样java代码实现

原文地址: https://www.cveoy.top/t/topic/bn2Y 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录