链表主要是不要在交换的过程中丢了
空间也需要节约
算法的一种要是思想就是减少重复计算
24. 两两交换链表中的节点
class Solution:
def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
if head == None or head.next == None:
return head
preHead = ListNode(0)
preHead.next = head
beforeTail = preHead # 记录上一组的结束
afterHead = head # 记录下一组的开始
cur = head
while cur!= None and cur.next != None:
#下一组的开始
afterHead = afterHead.next.next
# 交换节点
beforeTail.next = cur.next
cur.next = afterHead
beforeTail.next.next = cur
# 移动到新的一组
beforeTail = beforeTail.next.next
cur = beforeTail.next
return preHead.next
19.删除链表的倒数第N个节点
leetcode 19.删除链表的倒数第N个节点
代码随想录
固定删除的长度,快指针的next是none了,就可以删除慢指针的下一个元素了
class Solution:
def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
preHead = ListNode(0)
preHead.next = head
slow = fast = preHead
for _ in range(n):
fast = fast.next
while fast.next != None:
slow = slow.next
fast = fast.next
slow.next = slow.next.next
return preHead.next
面试题 02.07. 链表相交
leetcode 面试题 02.07. 链表相交
代码随想录
- 链表相交和后面的环形链表可以合并起来
将其中一个链表的头尾链接起来(记得保留位置,方便恢复),然后就可以调用环形链表(数学解),找入口节点。
class Solution:
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
if headA == None or headB == None:
return None
# 空间换时间
listNodeSet = set()
while headA != None:
listNodeSet.add(headA)
headA = headA.next
while headB != None:
if headB in listNodeSet:
break
headB = headB.next
return headB
# 空间复杂度为O(1)的话就是把其中一个链接起来形成一个环,然后通过找环的入口(如果相交)-用数学上的方式了
# 需要注意的点,最后需要将环给断开
142.环形链表II
环形链表有一个数学上的等式,见下图
class Solution:
def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]:
if head == None or head.next == None:
return None
# 使用set
# listNodeSet = set()
# while head.next != None:
# if head in listNodeSet:
# return head
# listNodeSet.add(head)
# head = head.next
# return None
# 使用set的方式有点太简单了,用空间换时间
# 数学上的等式
preHead = ListNode(0)
preHead.next = head
slow = preHead
fast = preHead
while fast.next != None and fast.next.next != None:
slow = slow.next
fast = fast.next.next
if fast == slow:
while preHead != slow:
preHead = preHead.next
slow = slow.next
return preHead
return None