LeetCode:206. 反转链表(python)
反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
进阶:你可以迭代或递归地反转链表。你能否用两种方法解决这道题?
思路:
- 迭代
- 记录 pre,cur,nex 指针进行翻转链表方向和迭代
- 递归
- 见代码注释
附代码(Python):
-
迭代
class ListNode: def __init__(self, x): self.val = x self.next = None # pre,cur,nex 指针迭代 class Solution: def reverseList(self, head): if not head: return None pre, cur = None, head while cur.next: nex = cur.next cur.next = pre pre = cur cur = nex cur.next = pre return cur
# 构建链表 head = cur = ListNode(None) for i in [1, 2, 3, 4, 5]: cur.next = ListNode(i) cur = cur.next head = head.next # 反转链表 test = Solution() res = test.reverseList(head) while res: print(res.val, end=' ') res = res.next
5 4 3 2 1
-
递归
class ListNode: def __init__(self, x): self.val = x self.next = None # 递归 class Solution: def reverseList(self, head): if head == None or head.next == None: # head==None 是为了防止传入的 head 为空;head.next==None 为递归的返回条件 return head cur = self.reverseList(head.next) # cur 第一次返回为链表尾端,即反转链表的头部,且将不断返回,不再更改 head.next.next = head # head 此时为前一节点,改变链表指向 head.next = None # 将新的尾节点指向 None,该尾节点不断更新 return cur
# 构建链表 head = cur = ListNode(None) for i in [1, 2, 3, 4, 5]: cur.next = ListNode(i) cur = cur.next head = head.next # 反转链表 test = Solution() res = test.reverseList(head) while res: print(res.val, end=' ') res = res.next
5 4 3 2 1