反转链表(两种Python解法)

时间:2020-07-03 21:41:43   收藏:0   阅读:160

题目:

反转一个单链表。

示例:

输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
进阶:
你可以迭代或递归地反转链表。你能否用两种方法解决这道题?

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reverse-linked-list

思路:

  主要需要注意反转过程中不要丢了节点。可以使用两个指针,也可以使用三个指针。

技术图片

技术图片

Python解法一:

1 class Solution:
2     def reverseList(self, head):
3         cur, prev = head, None 
4         while cur:
5             temp = cur.next
6             cur.next = prev
7             prev = cur
8             cur = temp
9         return prev

Python解法二:

 1 class Solution:
 2     def reverseList(self, head):
 3         if head == None or head.next == None:
 4             return head
 5         prev = None
 6         cur = head
 7         post = head.next
 8         
 9         while post:
10             cur.next = prev
11             prev = cur
12             cur = post
13             post = post.next
14         cur.next = prev
15         return cur
评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!