24. 两两交换链表中的节点
使用交换的写法
# Definition for singly-linked list.
# 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_node = ListNode(0,head)
cur = dummy_node
while cur.next and cur.next.next:
temp = cur.next
temp1 = cur.next.next.next
cur.next = cur.next.next
cur.next.next = temp
cur.next.next.next = temp1
cur = cur.next.next
return dummy_node.next
使用并行交换的写法:
class Solution:
def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
dummy_node = ListNode(0,head)
cur = dummy_node
while cur.next and cur.next.next:
temp = cur.next
temp1 = cur.next.next.next
cur.next,cur.next.next, = cur.next.next,temp,
cur = cur.next.next
cur.next = temp1
return dummy_node.next
19
# 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]:
dummy_node = ListNode(0,head)
slow,fast = dummy_node,dummy_node
for _ in range(n):
fast = fast.next
while fast.next:
fast = fast.next
slow = slow.next
slow.next = slow.next.next
return dummy_node.next
# 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]:
dummy_node = ListNode(0,head)
slow,fast = dummy_node,dummy_node
for _ in range(n):
fast = fast.next
while fast.next:
fast = fast.next
slow = slow.next
slow.next = slow.next.next
return dummy_node.next
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
lenA, lenB = 0,0
cur = headA
# 求出两个链表长度
while cur:
cur = cur.next
lenA += 1
cur = headB
while cur:
cur = cur.next
lenB += 1
# 择出长链表表头
curA,curB = headA,headB
if lenA > lenB:
curA, curB = curB, curA
lenA, lenB = lenB, lenA
# 末位对齐
for _ in range(lenB-lenA):
curB = curB.next
while curA:
if curA == curB:
return curA
else:
curA = curA.next
curB = curB.next
return None
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]:
slow,fast = head,head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
slow = head
# 再走一个z
while slow != fast:
slow = slow.next
fast = fast.next
return slow
return None