doc: 2025-10-24打卡
This commit is contained in:
52
143.reorder-list.java
Normal file
52
143.reorder-list.java
Normal file
@@ -0,0 +1,52 @@
|
||||
/*
|
||||
* @lc app=leetcode id=143 lang=java
|
||||
*
|
||||
* [143] Reorder List
|
||||
*/
|
||||
|
||||
// @lc code=start
|
||||
/**
|
||||
* 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 {
|
||||
public void reorderList(ListNode head) {
|
||||
if(head == null || head.next == null) {
|
||||
return;
|
||||
}
|
||||
// reverse the right side and merge
|
||||
ListNode d1 = new ListNode(0);
|
||||
d1.next = head;
|
||||
ListNode slow = d1, fast = d1;
|
||||
while(fast!=null && fast.next!=null) {
|
||||
fast = fast.next.next;
|
||||
slow = slow.next;
|
||||
}
|
||||
ListNode rh = slow.next, lh = head;
|
||||
slow.next = null;
|
||||
// reverse the right half
|
||||
ListNode prev = null, cur = rh, t;
|
||||
while(cur != null) {
|
||||
t = cur.next;
|
||||
cur.next = prev;
|
||||
prev = cur;
|
||||
cur = t;
|
||||
}
|
||||
rh = prev;
|
||||
// merge the two linkedlist
|
||||
while(rh != null) {
|
||||
t = lh.next;
|
||||
lh.next = rh;
|
||||
lh = rh;
|
||||
rh = t;
|
||||
}
|
||||
}
|
||||
}
|
||||
// @lc code=end
|
||||
|
||||
Reference in New Issue
Block a user