lintcode练习-36. 翻转链表 II

36. 翻转链表 II

翻转链表中第m个节点到第n个节点的部分

样例

给出链表1->2->3->4->5->null, m = 2 和n = 4,返回1->4->3->2->5->null

挑战

在原地一次翻转完成

注意事项

m,n满足1 ≤ m ≤ n ≤ 链表长度

实现代码:

"""
Definition of ListNode
class ListNode(object):
    def __init__(self, val, next=None):
        self.val = val
        self.next = next
"""

class Solution:
    """
    @param head: ListNode head is the head of the linked list 
    @param m: An integer
    @param n: An integer
    @return: The head of the reversed ListNode
    """
    
    '''
    def reverseBetween(self, head, m, n):
        # write your code here
        #将链表转成数组,取巧的方法
        cur = head
        temp_list = []
        while cur:
            temp_list.append(cur.val)
            cur = cur.next
        
        changed_list = temp_list[m-1:n]
        changed_list.reverse()
        reversed_list = temp_list[:m-1] + changed_list + temp_list[n:]
        
        dummy = ListNode(0)
        pre = dummy
        for item in reversed_list:
            pre.next = ListNode(item)
            pre = pre.next
        
        return dummy.next
    '''
    
    def reverseBetween(self, head, m, n):
        # write your code here
        if m == n:
            return head
        
        dummy = ListNode(0)
        dummy.next = head
        
        #翻转部分
        mpre = dummy
        mcur = head
        
        #定位到翻转部分
        for i in range(m - 1):
            mpre = mpre.next
            mcur = mpre.next
        
        #定义进行交换的拷贝变量
        temp_cur = mcur
        temp_post = temp_cur.next
        
        #对n-m的结点进行翻转
        for i in range(n-m):
            tmp = temp_post.next
            temp_post.next = temp_cur
            temp_cur = temp_post
            temp_post = tmp
        
        #更新交换后的结点
        mpre.next = temp_cur
        mcur.next = temp_post
        
        return dummy.next
            
            
                
                

 

 

猜你喜欢

转载自blog.csdn.net/qq_36387683/article/details/81669054