Open larscheng opened 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)
25. K 个一组翻转链表