leetCode第206题 反转链表。
链接:https://leetcode-cn.com/problems/reverse-linked-list
给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。
示例1:
示例2:
示例 3:
输入:head = []
输出:[]
提示:
链表中节点的数目范围是 [0, 5000]
-5000 <= Node.val <= 5000
提示:
链表中节点的数目范围是 [0, 5000]
-5000 <= Node.val <= 5000
进阶:链表可以选用迭代或递归方式完成反转。你能否用两种方法解决这道题?
## python3
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
if head == None:
return None
pre = None
cur = head
nex = head.next
while cur != None:
cur.next = pre
cur = nex
nex = nex.next
return pre
## python3
class Solution1:
tail = ListNode()
def reverseList(self, head: ListNode) -> ListNode:
if head == None:
return head
head = self.digui(head)
return self.tail
def digui(self, head: ListNode) -> ListNode:
if head.next == None:
self.tail = head
return head
else:
temp = self.digui(head.next)
temp.next = head
head.next = None
return head