演算法38--Swap Nodes in Pairs
阿新 • • 發佈:2018-11-25
Given a linked list, swap every two adjacent nodes and return its head.
Example:
Given1->2->3->4
, you should return the list as2->1->4->3
Note:
- Your algorithm should use only constant extra space.
- You may not modify the values in the list's nodes, only nodes itself may be changed
給定一個單鏈表,依次交換每兩個節點。
思路一利用三指標pre pcur pnext來依次操作:
每次遍歷以兩個節點為單位 pre---pcur--pnext
執行操作 交換兩個指標
pcur.next = pnext.next
pnext.next = pcur
pre.next = pcur
依次移動指標,進行下一次迴圈,但是要主要空指標的驗證
pre = pcur
pcur = pcur.next
pnext = pcur.next
class Solution: def swapPairs(self, head): """ :type head: ListNode :rtype: ListNode """ if head==None or head.next==None: return head first = head second = head.next first.next = second.next second.next = first head = second if first.next==None: return head pcur = first.next if pcur==None or pcur.next==None: return head pnext = pcur.next pre = first while pcur!= None and pnext!=None: pcur.next = pnext.next pnext.next = pcur pre.next = pnext pre = pcur pcur = pcur.next if pcur!=None and pcur.next!=None: pnext = pcur.next return head
思路二利用遞迴思想來實現:
head--head.next---head.next.next----
假定head.next以後節點已經交換完成且頭指標為newhead
head--head.next---newhead
指標交換,完成交換
next = head.next
head.next = newhead
next.next = head
return next
遞迴的基準條件是head==None 或者head.next==None 此時說明沒有節點可以交換,返回即可
class Solution: def swapPairs(self, head): """ :type head: ListNode :rtype: ListNode """ if head!=None and head.next!=None: newhead = self.swapPairs(head.next.next) next = head.next head.next = newhead next.next = head return next else: return head