python链表翻转_反转链表(两种Python解法)
題目:
反轉(zhuǎn)一個(gè)單鏈表。
示例:
輸入: 1->2->3->4->5->NULL
輸出: 5->4->3->2->1->NULL
進(jìn)階:
你可以迭代或遞歸地反轉(zhuǎn)鏈表。你能否用兩種方法解決這道題?
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/reverse-linked-list
思路:
主要需要注意反轉(zhuǎn)過程中不要丟了節(jié)點(diǎn)。可以使用兩個(gè)指針,也可以使用三個(gè)指針。
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
《新程序員》:云原生和全面數(shù)字化實(shí)踐50位技術(shù)專家共同創(chuàng)作,文字、視頻、音頻交互閱讀總結(jié)
以上是生活随笔為你收集整理的python链表翻转_反转链表(两种Python解法)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 广发钻石信用卡申请条件
- 下一篇: 索尼的笔记本怎么进bios 索尼笔记本如