143. 重排链表
首先
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
void reorderList(ListNode* head) {
ListNode* fast = head;
ListNode* slow = head;
while (fast != nullptr && fast->next != nullptr){
slow = slow->next;
fast = fast->next->next;
}
ListNode* cur = slow->next;
slow->next = nullptr;
ListNode* pre = nullptr;
while(cur){
ListNode* nxt = cur->next;
cur->next = pre;
pre = cur;
cur = nxt;
}
cur = head;
while(pre != nullptr){
ListNode *t = pre->next;
pre->next = cur->next;
cur->next = pre;
cur = pre->next;
pre = t;
}
}
};
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reorderList(self, head: Optional[ListNode]) -> None:
"""
Do not return anything, modify head in-place instead.
"""
def reverse(node):
pre = None
cur = node
while cur:
nxt = cur.next
cur.next = pre
pre = cur
cur = nxt
return pre
pre = ListNode()
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
mid = reverse(slow.next)
slow.next = None
cur = pre
while head and mid:
cur.next = head
head = head.next
cur = cur.next
cur.next = mid
mid = mid.next
cur = cur.next
cur.next = head if head else mid