24--leetcode--倆倆交換鏈表中的結點

# 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):
        p=ListNode(0)                                                      #0(頭結點)->1(交換對前)->2(交換對後)->3(後結點)

                                                                                     #交換一對後爲0->2->1->3
        p.next=head
        h1=p                                                                     #操作對象爲頭結點+1對鏈表(後移後頭結點爲要交換的鏈表對之前那個)
        while h1.next and h1.next.next:
            h2=h1.next
            h1.next=h2.next
            h2.next=h2.next.next #h1.next.next               #先交換  1.頭 ->交換對後,2.交換對前->後結點,3交換對後->交換對前,4頭結                                                                                          點往後倆個
            h1.next.next=h2
            h1=h1.next.next
        return p.next
        """
        :type head: ListNode
        :rtype: ListNode
        """
        

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