leetcode 206 反转链表的三种解法

方法一:递归法

#递归法
class Solution:
    def reverseList(self, head: ListNode) -> ListNode:
        if head==None or head.next==None:
            return head
        #反转后的末尾 也就是第一个
        cur=self.reverseList(head.next)
        head.next.next=head
        head.next=None
        return cur

方法二:
入栈 出栈

#用栈
class Solution:
    def reverseList(self, head: ListNode) -> ListNode:
        stack=[]
        p=head
        while p!=None:
            stack.append(p.val)
            p=p.next
        p=head
        while stack:
            p.val=stack.pop()
            p=p.next
       
        return head

方法三:迭代法

#迭代法 最好理解的一种方法
class Solution:
    def reverseList(self, head: ListNode) -> ListNode:
        cur=head
        pre=None
        while cur!=None:
            cur_next=cur.next
            cur.next=pre
            pre=cur
            cur=cur_next
        return pre
发布了16 篇原创文章 · 获赞 3 · 访问量 1072

猜你喜欢

转载自blog.csdn.net/weixin_39666736/article/details/104059823
今日推荐