Files
leetcode/143.reorder-list.java
2025-10-24 16:32:48 +08:00

53 lines
1.2 KiB
Java

/*
* @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