2

【LeetCode】LinkedList相关题目

 2 years ago
source link: https://www.guofei.site/2022/03/05/linked.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

【LeetCode】LinkedList相关题目

2022年03月05日    Author:Guofei

文章归类: 0x81_数据结构与算法    文章编号: 593


版权声明:本文作者是郭飞。转载随意,但需要标明原文链接,并通知本人
原文链接:https://www.guofei.site/2022/03/05/linked.html

Edit

92. Reverse Linked List II

反转链表总是要在至上画一画,有固定模式吗?

class Solution:
    def reverseBetween(self, head: ListNode, left: int, right: int) -> ListNode:
        dummy=ListNode(val=None,next=head)
        curr1=curr2=dummy
        for _ in range(right):
            curr2=curr2.next

        for _ in range(left-1):
            curr1=curr1.next

        for _ in range(right-left):
            tmp=curr1.next
            curr1.next=curr1.next.next
            tmp.next=curr2.next
            curr2.next=tmp

        return dummy.next

206. Reverse Linked List

class Solution:
    def reverseList(self, head: ListNode) -> ListNode:
        if head is None:
            return None
        dummy = ListNode(val=None,next=head)

        curr=dummy
        while curr.next:
            curr=curr.next

        while dummy.next is not curr:
            tmp=dummy.next
            dummy.next=dummy.next.next
            tmp.next=curr.next
            curr.next=tmp

        return dummy.next

有个极妙的题解,可惜可读性看来很差

class Solution:
    def reverseList(self, head):
        p, rev = head, None
        while p:
            rev, rev.next, p = p, rev, p.next
        return rev

您的支持将鼓励我继续创作!


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK