-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathReorderList.java
71 lines (56 loc) · 2.09 KB
/
ReorderList.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
//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; }
}
public class ReorderList {
public void reorderList(ListNode head) {
if (head == null || head.next == null) {
// If the list is empty or has only one node, no reordering is needed.
return;
}
// Step 1: Find the middle of the linked list.
ListNode middle = findMiddle(head);
// Step 2: Reverse the second half of the linked list.
ListNode reversedSecondHalf = reverseLinkedList(middle.next);
middle.next = null; // Break the original list into two halves.
// Step 3: Merge the two halves.
mergeLists(head, reversedSecondHalf);
}
// Helper function to find the middle of the linked list using the slow and fast pointer approach.
private ListNode findMiddle(ListNode head) {
ListNode slow = head;
ListNode fast = head;
while (fast != null && fast.next != null && fast.next.next != null) {
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
// Helper function to reverse a linked list.
private ListNode reverseLinkedList(ListNode head) {
ListNode prev = null;
ListNode current = head;
while (current != null) {
ListNode nextNode = current.next;
current.next = prev;
prev = current;
current = nextNode;
}
return prev; // 'prev' is the new head of the reversed list.
}
// Helper function to merge two linked lists by interleaving their nodes.
private void mergeLists(ListNode list1, ListNode list2) {
while (list1 != null && list2 != null) {
ListNode nextList1 = list1.next;
ListNode nextList2 = list2.next;
list1.next = list2;
list2.next = nextList1;
list1 = nextList1;
list2 = nextList2;
}
}
}