代码随想录训练营第四天|24|19|02.07|142

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

构建虚拟头节点,然后要用的都标上t1,t2,t3,画个图把逻辑理清

class Solution:
    def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
        dummy_head = ListNode(next=head)
        cur = dummy_head

        while cur.next and cur.next.next : # 注意这个也有顺序,反了会报错
            t1 = cur.next
            t2 = cur.next.next
            t3 = cur.next.next.next

            cur.next = t2
            t2.next = t1
            t1.next = t3
            cur = cur.next.next
            
        return dummy_head.next

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

用快慢指针,目的是找到要删除的节点的前一个节点。一开始脑子宕机了。

class Solution:
    def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
        dummy_head = ListNode(next = head)
        slow = dummy_head
        fast = dummy_head

        for i in range(n+1):
            fast = fast.next

        while fast:
            slow = slow.next
            fast = fast.next
        
        slow.next = slow.next.next

        return dummy_head.next

面试题 02.07. 链表相交

先找出两个链表的长度,然后让长的多走出差值,再找到相等的节点就是交点。

class Solution:
    def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
        cur = headA
        lenA, lenB = 0,0
        while cur :
            cur = cur.next
            lenA += 1
        cur = headB
        while cur:
            cur = cur.next
            lenB += 1
        curA,curB = headA,headB
        if lenA > lenB: # 保证lenB更大
            curA,curB = headB,headA
            lenA, lenB = lenB,lenA
        for _ in range(lenB-lenA):
            curB = curB.next
        while curA:
            if curA == curB:
                return curA
            else:
                curA=curA.next
                curB = curB.next

        return None
        

142.环形链表II

主要是知道快指针一次走两步如果能和慢指针相遇就一定能环

根据数学推导相遇后 慢指针一定和从相遇点出发的快节点在环的位置再次相遇

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

class Solution:
    def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]:
        slow =  head
        fast = head
        while fast and fast.next:
            slow = slow.next
            fast = fast.next.next

            if slow == fast:
                slow = head
                while slow!=fast:
                    slow=slow.next
                    fast = fast.next
                return slow
        return None

        

全部评论

相关推荐

点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务