python實現 LeetCode24——Swap Nodes in Pairs

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.

本題的思路是先虛擬一個新的頭節點,連接現有頭節點,令p指向頭節點,q指向頭節點後面的節點,然後連接方式我下圖所示,按照①,②,③的順序連接,①X,②X,③X代表①,②,③連接時斷開的。


leetcode代碼

class Solution():
    def swapPairs(self, head):
        if head==None or head.next==None:
            return head
        else:
            start=ListNode(0)
            start.next=head
            p=start
            q=start.next
            while q!=None and q.next!=None:
                p.next=q.next
                q.next=p.next.next
                p.next.next=q
                p=q
                q=q.next
            return start.next
包含測試用例的代碼
# -*- coding: utf-8 -*
class ListNode(object):
    def __init__(self,val,p=None):
        self.data = val
        self.next = p

class list(object):
    def initlist(self,data):
        self.head = ListNode(data[0])
        p = self.head
        for i in data[1:]:
            node = ListNode(i)
            p.next = node
            p = p.next

class Solution():
    def swapPairs(self, head):
        if head==None or head.next==None:
            return head
        else:
            start=ListNode(0)
            start.next=head
            p=start
            q=start.next
            while q!=None and q.next!=None:
                p.next=q.next
                q.next=p.next.next
                p.next.next=q
                p=q
                q=q.next
            return start.next
    def shuchu(self,head):
        p=head
        while p!=None:
            print p.data
            p=p.next
s = Solution()
l=list()
l.initlist([])
p=s.swapPairs(l.head)
s.shuchu(p)



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章