基于Python實現2種反轉鏈表方法代碼實例
題目:
反轉一個單鏈表。
示例:
輸入: 1->2->3->4->5->NULL
輸出: 5->4->3->2->1->NULL
進階:
你可以迭代或遞歸地反轉鏈表。你能否用兩種方法解決這道題?
思路:
主要需要注意反轉過程中不要丟了節點。可以使用兩個指針,也可以使用三個指針。
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
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。
相關文章:
1. IIS Express 取代 ASP.NET Development Server的配置方法2. Spring-Richclient 0.1.0 發布3. Express 框架中使用 EJS 模板引擎并結合 silly-datetime 庫進行日期格式化的實現方法4. IntelliJ IDEA設置條件斷點的方法步驟5. IntelliJ Idea2017如何修改緩存文件的路徑6. Intellij IDEA 旗艦版創建 Spring MVC 項目踩過的坑7. Python使用oslo.vmware管理ESXI虛擬機的示例參考8. Jsp中request的3個基礎實踐9. python flask框架快速入門10. 淺談SpringMVC jsp前臺獲取參數的方式 EL表達式
