python链表翻转_反转链表(两种Python解法)
題目:
反轉一個單鏈表。
示例:
輸入: 1->2->3->4->5->NULL
輸出: 5->4->3->2->1->NULL
進階:
你可以迭代或遞歸地反轉鏈表。你能否用兩種方法解決這道題?
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/reverse-linked-list
思路:
主要需要注意反轉過程中不要丟了節點。可以使用兩個指針,也可以使用三個指針。
Python解法一:
1 classSolution:2 defreverseList(self, head):3 cur, prev =head, None4 whilecur:5 temp =cur.next6 cur.next =prev7 prev =cur8 cur =temp9 return prev
Python解法二:
1 classSolution:2 defreverseList(self, head):3 if head == None or head.next ==None:4 returnhead5 prev =None6 cur =head7 post =head.next8
9 whilepost:10 cur.next =prev11 prev =cur12 cur =post13 post =post.next14 cur.next =prev15 return cur
原文地址:https://www.cnblogs.com/kongzimengzixiaozhuzi/p/13232395.html
《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀總結
以上是生活随笔為你收集整理的python链表翻转_反转链表(两种Python解法)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 广发钻石信用卡申请条件
- 下一篇: python绘制折线图中文图例不显示_p