Leetcode Reorder List

Source: Internet
Author: User

Leetcode Problem Solving Reorder List original problem

One-way linked list l0→l1→ ... →ln-1→ln converted to l0→ln→l1→ln-1→l2→ln-2→ ... form, which takes a node from the head and a node from the tail until the original linked list is converted into a new linked list.

Note the point:

    • Don't apply for extra space
    • Do not modify the value of a node

Example:

Input: {1,2,3,4}

Output: {1,4,2,3}

Thinking of solving problems

Since it is a one-way linked list, it is difficult to take elements from the tail, so we have to reverse the list, and because we are taking elements from both ends, we only need to reverse the second half of the list. We first get the middle node of the linked list by a fast and slow pointer, and we truncate the list. Then the second half of the linked list is flipped, and then the elements are extracted from the two linked lists in turn to connect. Note that it is important to note which linked list is longer when truncating, and do not omit elements when merging.

AC Source
 class solution(object):     def reorderlist(self, head):        "" " : Type head:ListNode:rtype:void does not return anything, modify head in-place instead. """        if  notHeadreturn        # splitFast = Slow = Head whileFast andFast.next:slow = Slow.next Fast = Fast.next.next Head1, head2 = head, Slow.next slow. Next =None        # ReverseCur, pre = head2,None         whileCur:nex = Cur.next Cur.next = Pre Pre = cur cur = NEX# MergeCur1, CUR2 = Head1, pre whileCur2:nex1, nex2 = Cur1.next, Cur2.next cur1.next = cur2 Cur2.next = nex1 cur1 , CUR2 = Nex1, nex2if__name__ = ="__main__":None

Welcome to my GitHub (Https://github.com/gavinfish/LeetCode-Python) to get the relevant source code.

Leetcode Reorder List

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.