题目:
反转一个单链表。
示例:
输入: 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