天天看點

LintCode:翻轉連結清單 II

LintCode:翻轉連結清單 II這裡寫連結内容

"""
Definition of ListNode

class ListNode(object):

    def __init__(self, val, next=None):
        self.val = val
        self.next = next
"""
class Solution:
    """
    @param head: The head of linked list
    @param m: start position
    @param n: end position
    """
    def reverseBetween(self, head, m, n):
        if m == :
            p1 = head
            j = 
            while j < n:
                j += 
                p1 = p1.next
            while(head != p1):
                tmp = ListNode()
                tmp.next = head.next
                head.next = p1.next
                p1.next = head
                head = tmp.next
            return head
        k = 
        l = 
        p1 = head
        p2 = head
        p3 = head
        while k < m-:
            k += 
            p1 = p1.next 
        p2 = p1.next
        while l < n:
            l += 
            p3 = p3.next
        p1.next = p3
        while(p2 != p3):
            tmp = ListNode()
            tmp.next = p2.next
            p2.next = p3.next
            p3.next = p2
            p2 = tmp.next

        return head