25. K 个一组翻转链表
给你一个链表,每 k 个节点一组进行翻转,请你返回翻转后的链表。
k 是一个正整数,它的值小于或等于链表的长度。
如果节点总数不是 k 的整数倍,那么请将最后剩余的节点保持原有顺序。
进阶:
你可以设计一个只使用常数额外空间的算法来解决此问题吗?
你不能只是单纯的改变节点内部的值,而是需要实际进行节点交换。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reverse-nodes-in-k-group
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
/**
 * Definition for singly-linked list.
 * public class ListNode {
 * int val;
 * ListNode next;
 * ListNode() {}
 * ListNode(int val) { this.val = val; }
 * ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    private ListNode reverse(ListNode head, ListNode end) {
        ListNode pre = null, cur = head, next;
        while (cur != end) {
            next = cur.next;
            cur.next = pre;
            pre = cur;
            cur = next;
        }
        return pre;
    }
    public ListNode reverseKGroup(ListNode head, int k) {
        if (head == null) {
            return head;
        }
        if (k <= 1) {
            return head;
        }
        int index = 0;
        ListNode dummy = new ListNode(), tail = dummy;
        
        ListNode start = null, cur = head, end, next;
        while (cur != null) {
            index++;
            next = cur.next;
            if (index % k == 1) {
                start = cur;
            } else if (index % k == 0) {
                end = cur;
                tail.next = reverse(start, end.next);
                tail = start;
            }
            cur = next;
        }
        if (index % k != 0) {
            tail.next = start;
        }
        return dummy.next;
    }
}
    心之所向,素履以往 生如逆旅,一苇以航

 
                
            
         浙公网安备 33010602011771号
浙公网安备 33010602011771号