Leetcode Reverse Linked List python 反转数字列表

Leetcode 206题 Reverse Linked List
Reverse a singly linked list.

Example:

Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL

Follow up:

A linked list can be reversed either iteratively or recursively. Could you implement both?


题目大意: 给你一个数字列表,要求你输出反转它。并且问能不能用迭代或者递归的方式?

思路一:
先大致一想,能不能用栈的方式,先压入栈,然后从栈底弹出,存入一个新的列表。

# 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:
        p = head
        newList=[]
        while p:   #存栈操作
            newList.insert(0,p.val)
            p = p.next
        
        p = head  #p再指向head
        for v in newList:  #插入
            p.val = v
            p = p.next
        return head

思路二:
迭代。 有点儿像C语言里的指针操作。还是比较简单的。

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def reverseList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        new_head = None #新列表
        while head:
            p = head  #P指向head
            head = head.next #head往下轮
            p.next = new_head  #p的下一个存进新列表中
            new_head = p  #最后头部的p放到最后一个
        return new_head

思路三:
递归。

# 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:
        if not head or not head.next:
            return head
        
        p = head.next
        n = self.reverseList(p)
        
        head.next = None
        p.next = head
        return n

2020/03/28
疫情中国的英国
鲍里斯也感染了
加油!

发布了20 篇原创文章 · 获赞 1 · 访问量 793

猜你喜欢

转载自blog.csdn.net/weixin_43860294/article/details/105170946