24. 两两交换链表中的节点
题目链接/文章讲解/视频讲解: 代码随想录
思路:创建虚拟节点,两两一循环,每次循环有四个节点参与。
1节点指向3节点是因为如果不写的话链表就会断开,返回的时候就不是链表了,例如1>2>3>4 就会变为2>1 4>3

# 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]:
node0 = dummy = ListNode(next=head)
node1 = head
while node1 and node1.next:
node2 = node1.next
node3 = node2.next
node0.next = node2
node2.next = node1
node1.next = node3
node0 = node1
node1 = node3
return dummy.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]:
dummy = ListNode(next=head)
slow = fast = dummy
for _ in range(n):
fast = fast.next
while fast.next:
slow = slow.next
fast = fast.next
slow.next = slow.next.next
return dummy.next
面试题 02.07. 链表相交
题目链接/文章讲解:代随想录
思路:快慢双指针,将两个单链表放在同一起点上
# 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: # 求链表A的长度
cur = cur.next
lenA += 1
cur = headB
while cur: # 求链表B的长度
cur = cur.next
lenB += 1
curA, curB = headA, headB
n = abs(lenA - lenB)
if lenA > lenB:
for _ in range(n):
curA = curA.next
else:
for _ in range(n):
curB = curB.next
while curA: # 遍历curA 和 curB,遇到相同则直接返回
if curA == curB:
return curA
else:
curA = curA.next
curB = curB.next
return None
142.环形链表II
题目链接/文章讲解/视频讲解:代码随想录
思路:快慢指针,若是一个还必会有一个相遇点,此时只需要知道还有多少步到入环点即可。
假设一圈步数为c,从头节点到入环处步数为a,相遇时slow走了b步,那么fast走了2b步,多走的步数为2b-b = kc-->b=kc。slow在环中走的步数为b-a-->kc-a,所以再走a步就到入环口了。
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]:
slow = head
fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
while slow != head:
slow = slow.next
head = head.next
return slow
return None
还可以使用集合的方法,遍历节点
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]:
s = set()
while head:
if head in s:
return head
s.add(head)
head = head.next
return None

2904

被折叠的 条评论
为什么被折叠?



