1. 程式人生 > >Leetcode篇:兩兩交換連結串列中的節點

Leetcode篇:兩兩交換連結串列中的節點


@author: ZZQ
@software: PyCharm
@file: swapPairs.py
@time: 2018/10/20 19:49
說明:給定一個連結串列,兩兩交換其中相鄰的節點,並返回交換後的連結串列。
示例:
給定 1->2->3->4, 你應該返回 2->1->4->3.
說明:
你的演算法只能使用常數的額外空間。
你不能只是單純的改變節點內部的值,而是需要實際的進行節點交換。
思路:
四個節點,分別記錄當前需要進行交換的兩個節點(first, second),以及這倆個節點的前後節點(pre, post)
然後每次只針對這四個節點進行交換即可。
注意考慮當輸入是空節點,一個節點,兩個節點,三個節點以及節點個數為奇數的情況。

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

class Solution(object):
    def __init__(self):
        pass

    def exchange(self, pre, first, second, post):
        first.next = None
        second.next = None
        first.next = post
        second.next = first
        pre.next = second
    def swapPairs(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if head is None or head.next is None:
            return head
        pre = ListNode(0)
        pre.next = head
        first = head
        second = head.next
        post = second.next
        p = pre
        while True:
            self.exchange(pre, first, second, post)
            pre = pre.next.next
            first = pre.next
            if first is None:
                break
            second = pre.next.next
            if second is None:
                break
            post = post.next.next
            if post is None:
                self.exchange(pre, first, second, post)
                break
        return p.next


if __name__ == "__main__":
    answer = Solution()
    l1 = ListNode(1)
    p1 = ListNode(2)
    p2 = ListNode(3)
    p3 = ListNode(4)
    p4 = ListNode(5)
    p5 = ListNode(6)
    l1.next = p1
    p1.next = p2
    p2.next = p3
    p3.next = p4
    p4.next = p5

    l2 = answer.swapPairs(l1)
    while l2 is not None:
        print l2.val
        l2 = l2.next