LeetCode Reverse Linked List II

Source: Internet
Author: User

LeetCode Reverse Linked List II
Reverse Linked List II

Original question

When only one traversal is performed and no additional space is requested, the elements m to n in a linked list are flipped over.

Note:

M and n meet the following conditions: 1 ≤ m ≤ n ≤ length of the linked list

Example:

Input: 1-> 2-> 3-> 4-> 5-> NULL, m = 2, n = 4

Output: 1-> 4-> 3-> 2-> 5-> NULL

Solutions

You can use the Reverse Linked List to flip the Linked List. Look, you can flip a section first, and then connect it to the front and back linked list. Because the first node may have to be flipped over, a false header node is added for consistency.

AC Source Code
# Definition for singly-linked list.class ListNode(object):    def __init__(self, x):        self.val = x        self.next = None    def to_list(self):        return [self.val] + self.next.to_list() if self.next else [self.val]class Solution(object):    def reverseBetween(self, head, m, n):        """        :type head: ListNode        :type m: int        :type n: int        :rtype: ListNode        """        dummy = ListNode(-1)        dummy.next = head        node = dummy        for __ in range(m - 1):            node = node.next        prev = node.next        curr = prev.next        for __ in range(n - m):            next = curr.next            curr.next = prev            prev = curr            curr = next        node.next.next = curr        node.next = prev        return dummy.nextif __name__ == "__main__":    n1 = ListNode(1)    n2 = ListNode(2)    n3 = ListNode(3)    n4 = ListNode(4)    n5 = ListNode(5)    n1.next = n2    n2.next = n3    n3.next = n4    n4.next = n5    r = Solution().reverseBetween(n1, 2, 4)    assert r.to_list() == [1, 4, 3, 2, 5]

Related Article

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.