LeetCode 题目-141.环形链表/160.相交链表(python实现)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_39884947/article/details/88625822

作为要准备踏入码农行业的人来说,要准备校招,怎么能不去刷刷LeetCode呢?

141.环形链表

  • 题目要求:
    给定一个链表,判断链表中是否有环。
    为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。

  • 示例:
    在这里插入图片描述
    在这里插入图片描述

你会发现其实根本没有pos这个参数传进去,所以可以不用理会它。
  • 分析:
    方法一:循环访问这个给定链表并将结点存入集合,并判断是否已经访问过
用集合不用列表是因为 判断元素在不在里面集合的效率比列表快得多
class Solution(object):
    def hasCycle(self, head):
        save = set() #用set是因为判断值是否存在比用list快
        cur = head 
        while cur is not None:
            if cur in save:
                return True
            else:
                save.add(cur)
                cur = cur.next
        return False   

方法二:使用快慢指针:一个指针步数是一(即每次移动一格),另一个步数是2 。如果有环则必然会在环内的一个点相遇。如果没有环步数为2的一定先一步结束碰到None

class Solution(object):
    def hasCycle(self, head):
        fast = slow = head
        while fast and fast.next:
            fast = fast.next.next
            slow = slow.next
            if slow == fast:
                return True
        return False

160.相交链表

  • 题目要求:
    编写一个程序,找到两个单链表相交的起始节点。

  • 示例:
    在这里插入图片描述
    在这里插入图片描述
    在这里插入图片描述

  • 方法一:将较长的链表先走|len(A)-len(B)|步, 然后同时遍历返回第一个公共节点.

class Solution(object):
    def getIntersectionNode(self, headA, headB):
        a ,b=headA,headB
        lena=0
        lenb=0
        while a:
            a= a.next
            lena +=1
        while b:
            b=b.next
            lenb +=1
        # 如果遍历到最后两个不相等就可以直接返回NULL
        if a!=b:
            return None
        if (lena<lenb):
            while(lena!=lenb):
                headB = headB.next
                lenb -= 1
        else:
            while (lena != lenb):
                headA = headA.next
                lena -= 1
        #此时已经把两个表的长度都统一固定了,要做的就是判断是不是有相同的
        while headA and headB:
            if headA==headB:
                return headA
            headB=headB.next
            headA=headA.next
        return None

方法二:同时对A和B进行遍历, 并且让到达末尾的指针指向另一个链表的头结点. 例如A: a->b->c->d; B: e->f->b->c->d 遍历时会相交于b(abcdefbcd, efbcdabcd).

class Solution(object):
    def getIntersectionNode(self, headA, headB):
        if headA==None or headB==None:
            return None
        p,q =headA,headB
        while p!=q:
            p =p.next if p else headB
            #if else 高级写法 不会的自行百度
            q =q.next if q else headA
        return p

猜你喜欢

转载自blog.csdn.net/qq_39884947/article/details/88625822