larscheng / algo

0 stars 0 forks source link

【Check 42】2024-04-02 - 25. K 个一组翻转链表 #143

Open larscheng opened 6 months ago

larscheng commented 6 months ago

25. K 个一组翻转链表

larscheng commented 6 months ago

思路

class Solution {

//O(n)/O(1)
public ListNode reverseKGroup(ListNode head, int k) {
    ListNode cur = head;
    int length = 0;
    while (cur!=null){
        cur = cur.next;
        length++;
    }
    ListNode dummy = new ListNode(0);
    ListNode temp  = dummy;
    cur = head;
    for (int i = 0; i+k <= length ; i+=k) {
        ListNode pre = null;
        ListNode tail = null;
        for (int j = 0; j < k; j++) {
            if (j==0){
                tail = cur;
            }
            //保留原始结构
            ListNode next = cur.next;
            //反转指向
            cur.next = pre;
            //继续遍历
            pre = cur;
            cur = next;

        }
        temp.next = pre;
        temp = tail ;
    }
    if (cur!=null){
        temp.next = cur;
    }
    return dummy.next;
}

}



### 复杂度
- 时间复杂度:O(n)
- 空间复杂度:O(1)