160.相交链表
返回两个链表相交的节点
class Solution(object):
def getIntersectionNode(self, headA, headB):
"""
:type head1, head1: ListNode
:rtype: ListNode
"""
if not headA and not headB:
return None
p1,p2=headA,headB
while(p1!=p2):
p1=p1.next if p1 else headB #短的接上长的,循环到长的也走完的时候,短和长的差便补上了。画图便可以理解
p2=p2.next if p2 else headA
return p1
19.删除链表的倒数第N个节点
返回链表的头结点。
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
'''快慢指针,之间相隔n个元素'''
class Solution(object):
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
fast=head
slow=head
for i in range(n):
fast=fast.next
if not fast:
return slow.next
while fast.next:
fast=fast.next
slow=slow.next
slow.next=slow.next.next
return head
21.合并两个有序链表
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
prehead = ListNode(0)
prev = prehead
while l1 and l2:
if l1.val <= l2.val:
prev.next = l1
l1 = l1.next
else:
prev.next = l2
l2 = l2.next
prev=prev.next
prev.next=l1 if l1 is not None else l2
return prehead.next