leetcode hot100

Source

21.合并两个有序链表

双指针秒了,注意判空

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
        p=list1 #较小的
        q=list2
        if p==None:
            return q
        if q==None:
            return p
        if  q.val<p.val:
            p,q=q,p
        head=p
        r=p
        p=p.next
        while p!=None and q!=None:
            if p.val<q.val:
                r.next=p
                p=p.next
            else:
                r.next=q
                q=q.next
            r=r.next
        if p!=None:
            r.next=p
        if q!=None:
            r.next=q
        return head

2.两数相加

先把链表变成数字相加,再把数字变成链表
注意循环的退出条件,循环的变量,注意逻辑的正确性,别犯困

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
        num=0
        p=l1
        q=l2
        cnt=1
        while p!=None:
           num+=p.val*cnt
           cnt*=10
           p=p.next
        cnt=1
        while q!=None:
            num+=q.val*cnt
            cnt*=10
            q=q.next
        
        remainder=num%10
        num//=10
        r=ListNode(remainder,None)
        l=r
        while num!=0:
            remainder=num%10
            s=ListNode(remainder,None)
            r.next=s
            r=s
            num=num//10
        return l

19. 删除链表的倒数第 N 个结点

我是拿个数组存了,不然得遍历两次链表,不过这样占用空间会比较多…

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
        node=[]
        p=head
        while p!=None:
            node.append(p)
            p=p.next
        length=len(node)
        trageti=length-n
        if trageti==0:#删除第一个节点
            head=node[trageti].next
        else:
            node[trageti-1].next=node[trageti].next
        return head