leetcode python3 简单题206. Reverse Linked List

1.编辑器

我使用的是win10+vscode+leetcode+python3
环境配置参见我的博客:
链接

2.第二百零六题

(1)题目
英文:
Reverse a singly linked list.

Example:

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

中文:
反转一个单链表。

示例:

输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reverse-linked-list

(2)解法
① 递归:先找到最后一个数3,然后依次接2,1,None就完成了
(耗时:56ms,内存:18.5M)

# 同样的代码贴上
# 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
        newH = self.reverseList(head.next)
        head.next.next = head
        head.next = None
        return newH

② 迭代:就是先在表头1下面改接None,然后依次在1的前面接上2,2前面接上3就完成了
(耗时:48ms,内存:14.5M)

# 同样经典代码贴上
# 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:
        cur, pre = head, None
        while cur:
            cur.next, pre, cur = pre, cur, cur.next
        return pre

注意:
1.cur.next, pre, cur = pre, cur, cur.next与下面的代码是不等价的!

            cur.next = pre
            pre = cur
            cur = cur.next

要等价,可以等效为:

            temp = cur.next
            cur.next = pre
            pre = cur
            cur = temp

因为多变量的赋值是会创建临时变量空间来存放的,所以不会只要是使用相同的变量名称,值都不会变!

2如果要本地测试解法②,直接运行下面的代码即可

class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None

class SingleLinkList:
    def __init__(self, node=None):
        self.__head = node

    def is_Empty(self):
        return self.__head is None

    def append(self, item):
        node = ListNode(item)
        if self.is_Empty():
            self.__head = node
        else:
            cur = self.__head
            while cur.next is not None: 
                cur = cur.next
            cur.next = node

    def find_head(self):
        return self.__head


class Solution:
    def reverseList(self, head: ListNode) -> ListNode:
        cur, pre = head, None
        while cur:
            cur.next, pre, cur = pre, cur, cur.next
        return pre


ls = SingleLinkList()
data = [1, 2, 3]
for i in data:
    ls.append(i)
print(type(ls))
mm = Solution()
res = mm.reverseList(ls.find_head())

while res:
    print(res.val, end='')
    res = res.next

3.补充一点

a=1
b=2
c=3
a, b, c = b, a+b, b
#输出
a=2
b=1+2=3
c=b=2
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值