Skip to content

Latest commit

 

History

History
35 lines (25 loc) · 755 Bytes

024._swap_nodes_in_pairs.md

File metadata and controls

35 lines (25 loc) · 755 Bytes

###24. Swap Nodes in Pairs

题目: https://leetcode.com/problems/swap-nodes-in-pairs/

难度 : Easy

看了hint,用loop做,每个node关系要弄清楚


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

        dummy = ListNode(-1)
        dummy.next = head
        
        cur = dummy

        while cur.next and cur.next.next:
            next_one, next_two, next_three = cur.next, cur.next.next, cur.next.next.next
            cur.next = next_two
            next_two.next = next_one
            next_one.next = next_three
            cur = next_one
        return dummy.next