Description
反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
Solution 迭代
使用nextNode缓存下一个节点。
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
pre = None
cur = head
while cur:
nextNode = cur.next
cur.next = pre
pre = cur
cur = nextNode
return pre
Solution 递归
从头至尾开始反转:1->2->3->N
- N<-1
- N<-1<-2
- N<-1<-2<-3
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
"""
- 使用循环能解决,使用递归也能够解决
- 递归层操作:循环修改相邻两个元素指针指向,使得后一个节点指针指向前一个节点
- 递归退出条件:递归推出条件其实也是使用循环时退出条件,cur is None,也就是后一个节点为空节点时退出递归。
"""
def helper(pre, cur):
if cur is None:
return pre
cur_next = cur.next
cur.next = pre
return helper(cur, cur_next)
return helper(None, head)
# 作者:wu-xian-sen-2
# 链接:https://leetcode-cn.com/problems/reverse-linked-list/solution/shi-yong-xun-huan-neng-jie-jue-shi-yong-di-gui-ye-/
# 来源:力扣(LeetCode)
# 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。