9/3 链表-力扣160 、203、206

160.相交链表

给你两个单链表的头节点 headAheadB ,请你找出并返回两个单链表相交的起始节点。如果两个链表不存在相交节点,返回 null

图示两个链表在节点 c1 开始相交

题目数据 保证 整个链式结构中不存在环。

注意,函数返回结果后,链表必须 保持其原始结构

思考:若有公共节点则两链表一定会在某一个节点相遇,获取两个链表长度,得到长度差值,长链表先走差值,此时两个链表剩余长度相同,则在相遇时获取到公共节点

注:python中获取链表长度靠遍历链表获得

在一个方法中调用同一个类中的另一个方法 self.方法名()

class Solution(object):
    def length(self, head):
        if not head:
            return 0
        len = 0
        while head:
            len += 1
            head = head.next
        return len


    def getIntersectionNode(self, headA, headB):
        """
        :type head1, head1: ListNode
        :rtype: ListNode
        """
        longl = headA
        shortl = headB
        l1 = self.length(headA)
        l2 = self.length(headB)
        if l1 >= l2:
            c = l1 - l2
        else:
            c = l2 - l1
            longl = headB
            shortl = headA
        while c:
            longl = longl.next
            c -= 1
        while longl and shortl and longl != shortl:
            longl = longl.next
            shortl = shortl.next
        if not longl or not shortl:
            return None
        else:
            return longl

203.移除链表元素

给你一个链表的头节点 head 和一个整数 val ,请你删除链表中所有满足 Node.val == val 的节点,并返回 新的头节点

示例 1:

输入:head = [1,2,6,3,4,5,6], val = 6
输出:[1,2,3,4,5]

思考:首先判断头节点与val值之间的关系,若头节点值等于val值则将头一直往后移,循环停止后判断头节点是否为空;若不为空,则遍历后续节点,改变指针起到删除作用

class Solution(object):
    def removeElements(self, head, val):
        """
        :type head: ListNode
        :type val: int
        :rtype: ListNode
        """
        while head and head.val == val:
            head = head.next
        if not head:
            return head
        pre = head
        p = head.next
        while p:
            if p.val == val:
                pre.next = p.next
                p = p.next
            else:
                pre = p
                p = p.next
        return head
        

206.反转链表

给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。

示例 1:

输入:head = [1,2,3,4,5]
输出:[5,4,3,2,1]

思考:生成一个固定的头节点,将链表的每个元素使用头插法插入到新链表中即可完成反转

class Solution(object):

    def reverseList(self, head):

        """

        :type head: ListNode

        :rtype: ListNode

        """

        if not head or not head.next:

            return head

        h = ListNode()

        h.next = None

        while head:

            p = head.next

            head.next = h.next

            h.next = head

            head = p

        return h.next

       

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值