力扣Hot 100题解之链表(Python版)第一题解析

一、160. 相交链表


  • 思路:双指针遍历全部两个链表,如果有公共节点那肯定会在公共节点相遇(可以自己推一下)。主要是如何跳转到另外一个
  • 代码
  • class ListNode:
    	def __init__(self, x):
    		self.val = x
    		self.next = node
    class Solution:
    	def getIntersectionNode(self, headA, headB):
    		p, q = headA, headB
    		while p is not q:
    			p = p.next if p else headB
    			q = q.next if q else headA
    		return p
    

    二、206. 反转链表

  • 思路:头插法
  • 代码
  • class ListNode:
    	def __init__(self, val, next):
    		self.val = val
    		self.next = next
    class Solution:
    	def reverseList(self, head):
    		pre = None
    		cur = head
    		while cur:
    			nxt = cur.next
    			cur.next = pre
    			pre = cur
    			cur = nxt
    		return pre
    

    三、234. 回文链表

    3.1. 876. 链表的中间结点

  • 思路:快慢指针
  • 代码
  • class Solution:
        def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]:
            t1 = t2 = head
            while t2 and t2.next:
                t1 = t1.next
                t2 = t2.next.next
            return t1
    

  • 思路:找到中间节点,并讲从中间节点开始反,然后依次对比
  • 代码
  • # Definition for singly-linked list.
    # class ListNode:
    #     def __init__(self, val=0, next=None):
    #         self.val = val
    #         self.next = next
    class Solution:
        def middleNode(self, head):
            t1 = t2 = head
            while t2 and t2.next:
                t1 = t1.next
                t2 = t2.next.next
            return t1
    
        def reverseList(self, head):
            pre = None
            cur = head
            while cur:
                nxt = cur.next  # 记录下一个节点
                cur.next = pre  # 头插法,上个节点作为新节点的后继
                pre = cur       # 头插法,新节点作为新的前节点
                cur = nxt
            return pre
    
        def isPalindrome(self, head: Optional[ListNode]) -> bool:
            midNode = self.middleNode(head)
            midHead = self.reverseList(midNode)
            while midHead:
                if head.val != midHead.val:
                    return False
                head = head.next
                midHead = midHead.next
            return True
    

    作者:Y1nhl

    物联沃分享整理
    物联沃-IOTWORD物联网 » 力扣Hot 100题解之链表(Python版)第一题解析

    发表回复