代码随想录day4

第一题

本题心得:

1、一定要判断是 是否定条件还是肯定条件。

肯定条件:画出临界成立情况的指针位置,写出成立条件,判断临界不成立情况

否定条件:画出临界不成立情况,写出否定条件

2.当链表顺序改变时,改变的箭头尾部元素要记录

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

class Solution(object):
    def swapPairs(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        dummy_head=ListNode(0,next=head)
        cur=dummy_head
        while cur.next and cur.next.next:
            temp=cur.next               #原本链接的需要存起来
            temp1=cur.next.next.next    #原本链接的需要存起来

            cur.next=cur.next.next
            cur.next.next=temp
            cur.next.next.next=temp1 
            cur= cur.next.next
        return dummy_head.next

题目二

快慢指针法

class ListNode(object):
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next
class Solution(object):
    def removeNthFromEnd(self, head, n):
        """
        :type head: ListNode
        :type n: int
        :rtype: ListNode
        """
        dummy_head=ListNode(0,next=head)

        fast=head
        slow=dummy_head

        size=0

        while fast:
            size+=1
            fast=fast.next

        for i in range(size-n):
            slow=slow.next
        slow.next=slow.next.next
        return dummy_head.next

第三题:

求出两个列表长度差n,将较长链表的头指针位置移动n隔位置,然后两个链表同时遍历,判断相等条件

第四题:

fast指针每次移动2个,slow指针每次移动1个。两个指针必定能够在环内相遇。当 相遇时,设置index1和index2,同时移动,相遇位置即为环的入口。

class Solution(object):
    def detectCycle(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        fast=head
        slow=head
        while fast and fast.next:
            fast=fast.next.next
            slow=slow.next
            if fast==slow:
                index1= fast
                index2= head
                while index1!=index2:
                    index1=index1.next
                    index2=index2.next
                return index2
        return None
        
        
        

  • 10
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值