两两交换链表中的节点
class ListNode:
def __init__(self,val = 0,next = None):
self.val = val
self.next = next
class Solution:
def transPairs(self,head)->ListNode:
dummyHead = ListNode(next = head)
cur = dummyHead
while cur.next and cur.next.next:
temp = cur.next
temp1 = cur.next.next.next
cur.next = temp.next
cur.next.next = temp
temp.next = temp1
cur = temp
return dummyHead.next
删除倒数第n个节点
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
dummyHead = ListNode(next = head)
fast = dummyHead
slow = dummyHead
for i in range(n+1):
fast = fast.next
while fast :
fast = fast.next
slow = slow.next
slow.next = slow.next.next
return dummyHead.next
链表相交
class Solution:
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
lenA, lenB = 0, 0
cur = headA
while cur: # 求链表A的长度
cur = cur.next
lenA += 1
cur = headB
while cur: # 求链表B的长度
cur = cur.next
lenB += 1
curA, curB = headA, headB
if lenA > lenB: # 让curB为最长链表的头,lenB为其长度
curA, curB = curB, curA
lenA, lenB = lenB, lenA
for _ in range(lenB - lenA): # 让curA和curB在同一起点上(末尾位置对齐)
curB = curB.next
while curA: # 遍历curA 和 curB,遇到相同则直接返回
if curA == curB:
return curA
else:
curA = curA.next
curB = curB.next
return None
环形链表
使用快慢指针
class Solution:
def detectCycle(self, head: ListNode) -> ListNode:
slow = head
fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
# If there is a cycle, the slow and fast pointers will eventually meet
if slow == fast:
# Move one of the pointers back to the start of the list
slow = head
while slow != fast:
slow = slow.next
fast = fast.next
return slow
# If there is no cycle, return None
return None