ninehills / blog

https://ninehills.tech
758 stars 68 forks source link

LeetCode-24. Swap Nodes in Pairs #40

Closed ninehills closed 7 years ago

ninehills commented 7 years ago

问题

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

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.

思路

思路就是循环换next,主要是处理边界条件

解答

class ListNode(object):
    def __init__(self, x):
        self.val = x
        self.next = None

    def __str__(self):
        return "Node({0}->[{1}])".format(self.val, self.next)

def init_list(l):
    before = None
    for i in l[::-1]:
        n = ListNode(i)
        n.next = before
        before = n
    return n

class Solution(object):
    def swapPairs(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        root = ListNode(None)
        root.next = head
        head = root
        while head.next != None and head.next.next != None:
            n = head.next
            nn = n.next
            nnn = nn.next
            head.next = nn
            nn.next = n
            n.next = nnn
            head = head.next.next
        return root.next

print Solution().swapPairs(init_list([1,2,3,4,5]))
ninehills commented 7 years ago

4 20170801