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 == 1:
            p1 = head
            j = 1
            while j < n:
                j += 1
                p1 = p1.next
            while(head != p1):
                tmp = ListNode(0)
                tmp.next = head.next
                head.next = p1.next
                p1.next = head
                head = tmp.next
            return head
        k = 1
        l = 1
        p1 = head
        p2 = head
        p3 = head
        while k < m-1:
            k += 1
            p1 = p1.next 
        p2 = p1.next
        while l < n:
            l += 1
            p3 = p3.next
        p1.next = p3
        while(p2 != p3):
            tmp = ListNode(0)
            tmp.next = p2.next
            p2.next = p3.next
            p3.next = p2
            p2 = tmp.next

        return head

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