算法训练第四天

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

思路:

这个感觉是个模拟类的题目,只要对链表的数据结构熟悉就能做出来

代码:

class Solution(object):
    def swapPairs(self, head):
        """
        :type head: Optional[ListNode]
        :rtype: Optional[ListNode]
        """
        if head is None:
            return head
        new_head = ListNode(next=head)
        pos = new_head
        while pos.next:
            a = pos.next
            b = pos.next.next
            if b is None:
                break
            a.next = b.next
            b.next = a
            pos.next = b
            pos = a
        return new_head.next

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

思路:

这里我选择的算法是统计链表的长度len,然后删除索引为len-n的节点即可。

代码:

class Solution(object):
    def removeNthFromEnd(self, head, n):
        """
        :type head: Optional[ListNode]
        :type n: int
        :rtype: Optional[ListNode]
        """
        length = 0
        pos = head
        while pos :
            length+=1
            pos = pos.next
        delet_pos = length-n
        new_head = ListNode(next=head)
        pos = new_head
        i = 0
        while i<delet_pos:
            pos = pos.next
            i+=1
        pos.next = pos.next.next
        return new_head.next

160.链表相交

思路:

这道题本来打算用两个while循环去暴力搜索的,但是提交的时候超时了,于是改变策略,因为两个链表相交是在后面部分,因此我们只需要获知两个链表的长度,给短的链表在前面补齐长度,然后一起遍历链表,找出相同位置即可。

代码:

class Solution(object):
    def getIntersectionNode(self, headA, headB):
        """
        :type head1, head1: ListNode
        :rtype: ListNode
        """
        # 统计两个链表的长度
        A_len = 0
        B_len = 0
        pos = headA 
        while pos !=None:
            A_len+=1
            pos = pos.next
        pos = headB
        while pos !=None:
            B_len+=1
            pos = pos.next
        # 在短的链表前面补齐
        while A_len<B_len:
            new_node = ListNode(0)
            new_node.next = headA
            headA = new_node
            A_len+=1
        while B_len<A_len:
            new_node = ListNode(0)
            new_node.next = headB
            headB = new_node
            B_len+=1
        # 从头遍历两个链表
        i = headA
        j = headB
        while i!=None and j!=None:
            if i==j:
                return i
            i = i.next
            j = j.next

142.环形链表II

思路:

这道题其实使用python去解很容易实现,只需开一个list记录遍历过的节点,然后每遍历一个节点用in去判断是否在list中,如果在,就把该节点返回即可。

代码:

class Solution(object):
    def detectCycle(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        arr = []
        pos = head
        while pos not in arr and pos:
            arr.append(pos)
            pos = pos.next
        return pos
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

kaiaaaa

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值