題目:
Given a linked list, swap every two adjacent nodes and return its head.
You may not modify the values in the list's nodes. Only nodes itself may be changed.
思路:
覺得題目沒有描述的很完整,例子也沒有... swap every two adjacent ??? <--怎麽定義的,會不會重複?
只能推測+程式驗證: 從左到右 每兩個為1組 組內對調 , 題目說不是改node的值,但其實直接改node值也OK。
對調的方式 很像 泡泡排序的片段程式碼:
把即將被賦值的先存起來,因為之後會用到。
比如說 先將一組中 較前方的存起來(tmp),再將後方的值取代前方的值,最後後方的值由一開始存起來的值取代。
正解:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def swapPairs(self, head: ListNode) -> ListNode:
dummyNode = ListNode()
dummyNode = head
'''
print(dummyNode)
print(head.val)
tmp = head.val
head.val = head.next.val
head.next.val = tmp
print(head.val)
print(head.next.val)
if head.next.next!=None:
head = head.next.next
tmp = head.val
head.val = head.next.val
head.next.val = tmp
print(head.val)
print(head.next.val)
print(head)
print(dummyNode)
return dummyNode
'''
while head!=None:
tmp = head.val
if head==None or head.next==None:
break
head.val = head.next.val
head.next.val = tmp
head = head.next.next
return dummyNode
Result: