[LinkedList]024 Swap Nodes in Pairs

  • 分類:LinkedList

  • 考察知識(shí)點(diǎn):LinkedList

  • 最優(yōu)解時(shí)間復(fù)雜度:**O(n) **

24. Swap Nodes in Pairs

Given a linked list, swap every two adjacent nodes and return its head.

Example:

Given 1->2->3->4, you should return the list as 2->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.

代碼:

我的解法:

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

class Solution:
    def swapPairs(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if head==None or head.next==None:
            return head
        
        dummy=ListNode(0)
        dummy.next=head
        l1=dummy
        l2=head
        
        while(l2!=None and l2.next!=None):
            
            new_head=l2.next.next
            
            l1.next=l2.next
            l2.next.next=l2
            l2.next=new_head
            
            l1=l2
            l2=l2.next
            
            
        return dummy.next

討論:

1.這道題在面試中出現(xiàn)頻率挺低的
2.這道題主要就是為了讓人搞明白鏈表的next到底是啥,會(huì)不會(huì)被繞暈(事實(shí)上我就覺得非常的暈,暈上天了@.@)

過程圖
Outcome
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi閱讀 7,872評(píng)論 0 10
  • 建設(shè)西北滬上遷, 奮進(jìn)時(shí)代薪火傳。 激勵(lì)交大為西部, 科技創(chuàng)新今承建。 2018.01.22 注:西安交大承建的“...
    卡斯特羅梁閱讀 486評(píng)論 0 0
  • 一個(gè)創(chuàng)業(yè)失敗過的人和一個(gè)創(chuàng)業(yè)成功過的人,他面臨下一次創(chuàng)業(yè)的時(shí)候哪一個(gè),成功的幾率更高呢? 我們先來說一個(gè),外科醫(yī)生...
    陳歌的小視野閱讀 437評(píng)論 0 4
  • 寫在前面 ORM框架,關(guān)系映射框架,只需要提供持久化類和數(shù)據(jù)庫表之間的關(guān)系,就可以在運(yùn)行時(shí)候進(jìn)行數(shù)據(jù)持久化,通常j...
    z七夜閱讀 3,550評(píng)論 11 28

友情鏈接更多精彩內(nèi)容