6.27 二刷链表

This commit is contained in:
zhangsan 2025-06-27 21:24:55 +08:00
parent 76f15247d7
commit b814779b7d
3 changed files with 37 additions and 6 deletions

View File

@ -22,6 +22,7 @@ import java.util.HashMap;
*/
//不会做 需要重做
//二刷不会 很妙的思路
public class CopyRandomList {
public Node copyRandomList(Node head) {
if (head == null)

View File

@ -13,12 +13,12 @@ public class ReverseKGroup {
// 反转 [head, tail] 这一段返回新的头和新的尾
private ListNode[] reverse(ListNode head, ListNode tail) {
ListNode prev = tail.next;
ListNode p = head;
ListNode cur = head;
while (prev != tail) {
ListNode nxt = p.next;
p.next = prev;
prev = p;
p = nxt;
ListNode nxt = cur.next;
cur.next = prev;
prev = cur;
cur = nxt;
}
// 反转后tail 变成新头head 变成新尾
return new ListNode[]{ tail, head };

View File

@ -8,11 +8,13 @@ import java.util.List;
* 题目 148. 排序链表 (sortList)
* 描述给你链表的头结点 head 请将其按 升序 排列并返回 排序后的链表
进阶你可以在 O(n log n) 时间复杂度和常数级空间复杂度下对链表进行排序吗
* 链接https://leetcode.cn/problems/sort-list/
*/
//二刷思路会但链表归并排序不会
public class SortList {
public ListNode sortList(ListNode head) {
public ListNode sortList2(ListNode head) {
ListNode cur=head;
List<Integer>list=new ArrayList<>();
while (cur!=null){
@ -28,4 +30,32 @@ public class SortList {
}
return newnode.next;
}
ListNode sortList(ListNode head) {
if (head == null || head.next == null) return head;
// 快慢指针找中点并断链
ListNode slow = head, fast = head.next;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
ListNode mid = slow.next;
slow.next = null;
// 递归排序左右两段
ListNode left = sortList(head);
ListNode right = sortList(mid);
// 合并
return merge(left, right);
}
ListNode merge(ListNode a, ListNode b) {
ListNode dummy = new ListNode(-1), p = dummy;
while (a != null && b != null) {
if (a.val <= b.val) { p.next = a; a = a.next; }
else { p.next = b; b = b.next; }
p = p.next;
}
p.next = (a != null ? a : b);
return dummy.next;
}
}