LeetCode 143. Reorder List

题目

LeetCode 143. Reorder List_第1张图片

思路

步骤:

  • 先找到链表最终间的节点;
  • 然后将后半部分链表反转;
  • 最后将前半部分链表和反转后的后半部分链表合并;

ps:很好的一道链表题,强烈推荐,考察了:

  • 如何查找终见节点;
  • 链表反转;
  • 链表合并;

代码

ListNode* reverseList(ListNode* head){
    ListNode* pre = nullptr;
    while(head)
    {
        ListNode* temp = head->next;
        head->next = pre;
        pre = head;
        head = temp;
    }
    return pre;
}

ListNode* findMiddle(ListNode* head){
    if(!head)
        return nullptr;
        
    ListNode* slow = head;
    ListNode* fast = head;
    while(fast->next && fast->next->next)
    {
        slow = slow->next;
        fast = fast->next->next;
    }
    return slow;
}

void reorderList(ListNode* head) {
    //find center node
    ListNode* first = findMiddle(head);
    if(!head)
        return;
    //reverse the second part list
    ListNode* second = first->next;
    second = reverseList(second);
    //merge two part lists
    first->next = nullptr;
    first = head;
    while(second)
    {
        ListNode* temp1 = first->next;
        ListNode* temp2 = second->next;
        first->next = second;
        second->next = temp1;
            
        first = temp1;
        second = temp2;
    }
}

你可能感兴趣的:(#,链表,#,LeetCode)