19. 删除链表的倒数第N个结点
题目链接:https://leetcode.cn/problems/remove-nth-node-from-end-of-list/
思路:快慢指针
class Solution:
def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
head_dummy = ListNode()
head_dummy.next = head
slow, fast = head_dummy,head_dummy
while n != 0:
fast = fast.next
n -= 1
while fast.next != None:
slow = slow.next
fast = fast.next
slow.next = slow.next.next
return head_dummy.next
02.07 链表相交
题目链接:https://leetcode.cn/problems/intersection-of-two-linked-lists-lcci/
思路:个人认为是双指针
class Solution:
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
if headA is None or headB is None:
return None
cur_A, cur_B = headA, headB
while cur_A != cur_B:
if cur_A.next != None:
cur_A = cur_A.next
else:
cur_A = headB
if cur_B.next != None:
cur_B = cur_B.next
else:
cur_B = headA
return cur_A
142.环形链表II
题目链接:https://leetcode.cn/problems/linked-list-cycle-ii/
思路:快慢指针
class Solution:
def detectCycle(self, head: ListNode) -> ListNode:
slow, fast = head, head
while fast is not None and fast.next is not None:
slow = slow.next
fast = fast.next.next
if slow == fast:
p = head
q = slow
while p != q:
p = p.next
q = q.next
return p
return None
24. 两两交换链表中的节点
题目链接:https://leetcode.cn/problems/swap-nodes-in-pairs/
思路:我觉得谈不上什么算法,完全是针对指针的应用
class Solution:
def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
res = ListNode(next = head)
pre = res
while pre.next is not None and pre.next.next is not None:
cur = pre.next
post = pre.next.next
cur.next = post.next
post.next = cur
pre.next = post
pre = cur
return res.next
思路和代码建议大家直接看算法随想录,我的代码可能和carl哥的有很多相似之处,因为不是第一次做了,希望谅解。
对于这一周的学习,做一个简单的总结。正如我的初衷,算法营可以很好的督促我,起到了很好的监督作用,并且也通过算法营学到了一些不知道的学习方法,比如在蹲坑或者路途中,用手机leetcode写代码,都能锻炼到基础能力,甚至心算能力。
相比于之前一刷的时候,这次大部分代码已经能够自己写出,但是仍旧有些细节问题,需要多加巩固。当然也由于学习方面的问题,时间能够分给算法的不多,但希望可以自勉吧。