24. 两两交换链表中的节点
代码
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
dummy_head= ListNode(next=head)
cur = dummy_head
while cur.next != None and cur.next.next!= None:
temp = cur.next
temp1 = cur.next.next.next
cur.next = cur.next.next
cur.next.next = temp
temp.next = temp1
cur = cur.next.next
return dummy_head.next
19.删除链表的倒数第N个节点
代码
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]:
dummpy_head = ListNode(next=head)
fast = dummpy_head
slow = dummpy_head
n += 1
for i in range(n):
if fast.next:
fast = fast.next
else:
return dummpy_head.next.next
while fast.next:
slow = slow.next
fast = fast.next
slow.next.next = slow.next.next.next
return dummpy_head.next