# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next classSolution: defremoveNthFromEnd(self, head: ListNode, n: int) -> ListNode: right = head left = head for i inrange(n): right = right.next if right == None: # 如果要删除的是头结点 left = left.next return left while right.next != None: left = left.next right = right.next left.next = left.next.next return head
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next classSolution: defswapPairs(self, head: ListNode) -> ListNode: if head == None: return head temp = ListNode(0, head) first = temp second = temp.next
while second and second.next: first.next = second.next second.next = second.next.next first.next.next = second
first = second second = second.next return temp.next