反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
进阶:
你可以迭代或递归地反转链表。你能否用两种方法解决这道题?
链接:https://leetcode-cn.com/problems/reverse-linked-list/
解法1:
看图说话
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
pred=None
cur=head
while cur!=None:
next=cur.next
cur.next=pred
pred=cur
cur=next
return pred
解法2:
普通递归
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
if head is None or head.next is None:
return head
next=head.next
reversehead=self.reverseList(next)
next.next=head
head.next=None
return reversehead
解法3:
尾递归
解题思路: 从头节点开始,递归反转它的每一个节点,直到 null ,思路和解法一类似
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
if head is None or head.next is None:
return head
cur=self.reverseList(head.next)
head.next.next=head
head.next=None
return cur