[leetcode: Python]24. Swap Nodes in Pairs

来源:互联网 发布:中国宏观经济数据分析 编辑:程序博客网 时间:2024/05/19 22:24

Given a linked list, swap every two adjacent nodes and return its head.

For example,
Given 1->2->3->4, you should return the list as 2->1->4->3.

Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.

Subscribe to see which companies asked this question.

方法一:49ms
交换的四个步骤如下图
这里加了个头结点。
这里写图片描述

# Definition for singly-linked list.# class ListNode(object):#     def __init__(self, x):#         self.val = x#         self.next = Noneclass Solution(object):    def swapPairs(self, head):        """        :type head: ListNode        :rtype: ListNode        """        if head is None or head.next is None:            return head        dummy = ListNode(0)        dummy.next = head        p = dummy        while p.next and p.next.next:            tmp = p.next.next            p.next.next = tmp.next            tmp.next = p.next            p.next = tmp            p = p.next.next        return dummy.next

方法二:38ms

# Definition for singly-linked list.# class ListNode(object):#     def __init__(self, x):#         self.val = x#         self.next = Noneclass Solution(object):    def swapPairs(self, head):        """        :type head: ListNode        :rtype: ListNode        """        pre = self        pre.next = head        while pre.next and pre.next.next :            a = pre.next            b = a.next            a.next = b.next            pre.next = b            b.next = a            pre = a        return self.next

方法三:35ms
递归

# Definition for singly-linked list.# class ListNode(object):#     def __init__(self, x):#         self.val = x#         self.next = Noneclass Solution(object):    def swapPairs(self, head):        """        :type head: ListNode        :rtype: ListNode        """        if not head or not head.next: return head        cur = head        head = cur.next        cur.next = self.swapPairs(head.next)        head.next = cur        return head        '''        if not head or not head.next: return head        dummy = ListNode(0)        dummy.next = head        cur = dummy        while cur.next and cur.next.next:            # 如果不方便检查空,把ref挪到while里面让while来查也是很好的            n1 = cur.next            n2 = cur.next.next            n1.next = n2.next            n2.next = n1            cur.next = n2            cur = n1        return dummy.next        '''
原创粉丝点击