原題地址: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