[leetcode]Swap Nodes in Pairs @ Python


原題地址:http://oj.leetcode.com/problems/swap-nodes-in-pairs/

題意:將鏈表中的節點兩兩交換。Given 1->2->3->4, you should return the list as 2->1->4->3.

解題思路:這題主要涉及到鏈表的操作,沒什么特別的技巧,注意不要出錯就好。最好加一個頭結點,操作起來會很方便。

代碼:

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    # @param a ListNode
    # @return a ListNode
    def swapPairs(self, head):
        if head == None or head.next == None:
            return head
        dummy = ListNode(0); dummy.next = head
        p = dummy
        while p.next and p.next.next:
            tmp = p.next.next
            p.next.next = tmp.next
            tmp.next = p.next
            p.next = tmp
            p = p.next.next
        return dummy.next
        

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM