基于Python實現(xiàn)2種反轉(zhuǎn)鏈表方法代碼實例
題目:
反轉(zhuǎn)一個單鏈表。
示例:
輸入: 1->2->3->4->5->NULL
輸出: 5->4->3->2->1->NULL
進階:
你可以迭代或遞歸地反轉(zhuǎn)鏈表。你能否用兩種方法解決這道題?
思路:
主要需要注意反轉(zhuǎn)過程中不要丟了節(jié)點。可以使用兩個指針,也可以使用三個指針。
Python解法一:
class Solution: def reverseList(self, head): cur, prev = head, None while cur: temp = cur.next cur.next = prev prev = cur cur = temp return prev
Python解法二:
class Solution: def reverseList(self, head): if head == None or head.next == None: return head prev = None cur = head post = head.next while post: cur.next = prev prev = cur cur = post post = post.next cur.next = prev return cur
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. idea修改背景顏色樣式的方法2. jsp EL表達式詳解3. asp知識整理筆記4(問答模式)4. IntelliJ IDEA 統(tǒng)一設(shè)置編碼為utf-8編碼的實現(xiàn)5. 解決ajax的delete、put方法接收不到參數(shù)的問題方法6. chat.asp聊天程序的編寫方法7. Django ORM實現(xiàn)按天獲取數(shù)據(jù)去重求和例子8. XML入門的常見問題(一)9. Jsp中request的3個基礎(chǔ)實踐10. 怎樣才能用js生成xmldom對象,并且在firefox中也實現(xiàn)xml數(shù)據(jù)島?
