为方便后续的使用查找,记录一下
函数包括:找到两个单链表相交的起始节点、反转单链表、删除链表中等于给定值 val 的所有节点
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def getIntersectionNode(self, headA, headB):
"""
:type head1, head1: ListNode
:rtype: ListNode
"""
"""
编写一个程序,找到两个单链表相交的起始节点。
"""
# 将两个链表拼接分别为长-短和短长,当值相等时则找到相交点,反之则不相交
p, q = headA, headB
while p != q:
p = p.next if p else headB
q = q.next if q else headA
return p
"""
反转单链表
"""
def reverseList(self, head: ListNode) -> ListNode:
# 头插法
prev = None
cure = head
while cure:
next = cure.next
cure.next = prev
prev = cure
cure = next
return prev
"""
删除链表中等于给定值 val 的所有节点
"""
def removeElements(self, head: ListNode, val: int) -> ListNode:
if not head:
return head
p = head
while p.next:
if p.next.val == val:
p.next = p.next.next
else:
p = p.next
if head.val == val:
if head.next:
head = head.next
else:
head = None
return head