24.?兩兩交換鏈表中的節(jié)點(diǎn)
給定一個(gè)鏈表岭洲,兩兩交換其中相鄰的節(jié)點(diǎn)陆馁,并返回交換后的鏈表恕出。
示例:
給定1->2->3->4, 你應(yīng)該返回2->1->4->3.
說明:
你的算法只能使用常數(shù)的額外空間谈截。
你不能只是單純的改變節(jié)點(diǎn)內(nèi)部的值,而是需要實(shí)際的進(jìn)行節(jié)點(diǎn)交換菠红。
# class ListNode:
#? ? def __init__(self, x):
#? ? ? ? self.val = x
#? ? ? ? self.next = None
class Solution:
? ? def swapPairs(self, head):
? ? ? ? """
? ? ? ? :type head: ListNode
? ? ? ? :rtype: ListNode
? ? ? ? """
? ? ? ? head = self.duigui(head)
? ? ? ? return head
? ? def duigui(self, tree):
? ? ? ? if tree == None or tree.next == None:
? ? ? ? ? ? return tree
? ? ? ? else:
? ? ? ? ? ? next_data = tree
? ? ? ? ? ? nnext_data = tree.next
? ? ? ? ? ? next_data.next = nnext_data.next
? ? ? ? ? ? nnext_data.next = next_data
? ? ? ? ? ? # tree.next = nnext_data
? ? ? ? ? ? next_data.next = self.duigui(next_data.next)
? ? ? ? ? ? return nnext_data