Problem: 143. 重排链表
🔔 原地翻转:是指在原有的链表上进行操作,而不是不允许建立有序表进行辅助操作。
🍻 线性表辅助法
/**
* 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) {
ListNode tmp = head;
// 使用线性表记录链表,可以O(n)的时间进行从前往后和从后往前的遍历
List<ListNode> list = new ArrayList<>();
while(tmp != null){
list.add(tmp);
tmp = tmp.next;
}
int i = 0, j = list.size() -1;
while(i < j){
list.get(i).next = list.get(j);
i++;
if(i == j){
break;
}
list.get(j).next = list.get(i);
j--;
}
list.get(i).next = null;
}
}
🍻 找中点 + 翻转链表 + 合并链表
class Solution {
public void reorderList(ListNode head) {
if (head == null) {
return;
}
ListNode mid = middleNode(head);
ListNode l1 = head;
ListNode l2 = mid.next;
mid.next = null;
l2 = reverseList(l2);
mergeList(l1, l2);
}
public ListNode middleNode(ListNode head) {
ListNode slow = head;
ListNode fast = head;
while (fast.next != null && fast.next.next != null) {
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
public ListNode reverseList(ListNode head) {
ListNode prev = null;
ListNode curr = head;
while (curr != null) {
ListNode nextTemp = curr.next;
curr.next = prev;
prev = curr;
curr = nextTemp;
}
return prev;
}
public void mergeList(ListNode l1, ListNode l2) {
ListNode l1_tmp;
ListNode l2_tmp;
while (l1 != null && l2 != null) {
l1_tmp = l1.next;
l2_tmp = l2.next;
l1.next = l2;
l1 = l1_tmp;
l2.next = l1;
l2 = l2_tmp;
}
}
}