美文网首页
24. Swap Nodes in Pairs

24. Swap Nodes in Pairs

作者: April63 | 来源:发表于2018-06-18 22:06 被阅读0次

阿里的面试题目:

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def swapPairs(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if head == None or head.next == None:
            return head
        pre = ListNode(0)
        pre.next = head
        first = head 
        second = head.next
        p = pre
        while first and second:
            first.next = second.next
            second.next = first
            p.next = second
            p = first
            first = first.next
            if first:
                second = first.next
        return pre.next

递归的做法,他们都是天才

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def swapPairs(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if head == None or head.next == None:
            return head
        new_head, head.next, new_head.next = head.next, self.swapPairs(head.next.next), head
        return new_head

相关文章

网友评论

      本文标题:24. Swap Nodes in Pairs

      本文链接:https://www.haomeiwen.com/subject/tohoeftx.html