2022-09-24

24. 两两交换链表中的节点

class Solution:
    def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
        if not head or not head.next:
            return head
        ret=head.next
        while head and head.next:
            n=head.next
            if n.next and n.next.next:
                nh=n.next.next
            else:
                nh=n.next
            t=n.next
            n.next=head
            head.next=nh
            head=t

        return ret
        

19.删除链表的倒数第N个节点

class Solution:
    def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
        t=ListNode(0,head)
        f=t
        s=t
        for _ in range(n):
            f=f.next
        while f and f.next:
            f=f.next
            s=s.next
        s.next=s.next.next
        return t.next
        
        

面试题 02.07. 链表相交

class Solution:
    def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> Optional[ListNode]:
        if not headA or not headB:
            return None
        a=headA
        b=headB
        while a!=b:

            if not a :
                a=headB
            else:
                a=a.next
            if not b :
                b=headA
            else:
                b=b.next
        return a

142.环形链表II


class Solution:
    def detectCycle(self, head: ListNode) -> ListNode:

        if not head or not head.next:
            return None
        f=head.next.next
        s=head.next
        while f and f.next and f.next.next and f!=s:
            
            f=f.next.next
            s=s.next
        if not f or not f.next or not f.next.next:
            return None
        t=head
        while t!=s:
            t=t.next
            s=s.next
        return s
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容