环的起点
对于一个给定的链表,返回环的入口节点,如果没有环,返回null
拓展: 你能给出不利用额外空间的解法么?
if not head:
return None
fast,slow=head,head # 用快慢指针,如果有环必定相遇 且因为快是慢的俩倍,多出来的慢走的
while fast and fast.next: # 就是环长度,这时快指正指向头结点继续走整个长度-环,刚好慢指针
fast=fast.next.next # 走完整个链表与快相遇
slow=slow.next
if fast==slow:
break
if not fast or not fast.next:
return None
fast=head
while fast!=slow:
fast=fast.next
slow=slow.next
return fast
19. 删除链表的倒数第N个节点
给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。
示例:
给定一个链表: 1->2->3->4->5, 和 n = 2.
当删除了倒数第二个节点后,链表变为 1->2->3->5.
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
if n==0 or not head:
return head
h=ListNode(0)
h.next=head # 用一个头结点指向head
fast,slow=h,h # 快慢指正都是头结点
for i in range(n): # 快指正先走n个
fast=fast.next
while fast.next: # 快慢 同步走
fast=fast.next
slow=slow.next
slow.next=slow.next.next # 慢指正的next修改
return h.next
143. 重排链表
给定一个单链表 L:L0→L1→…→Ln-1→Ln ,
将其重新排列后变为: L0→Ln→L1→Ln-1→L2→Ln-2→…
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
示例 1:
给定链表 1->2->3->4, 重新排列为 1->4->2->3.
示例 2:
给定链表 1->2->3->4->5, 重新排列为 1->5->2->4->3.
def findmid(head):
first,last=head.next,head
while first and first.next:
first=first.next.next
last=last.next
return last
def reverseList(head):
pre=None
now=head
while now: # 判断now
temp=now.next
now.next=pre
pre=now # 连续赋值时注意下
now=temp
return pre # 返回pre
if not head:
return head
mid=findmid(head)
r=mid.next
mid.next=None
l=head
r=reverseList(r)
while l and r:
templ=l.next
tempr=r.next
l.next=r
r.next=templ
l=templ
r=tempr