边看题解,边学习 有点意思
这个给了这个ListCode的定义: 定义for 简单的链表 这个有2个属性,一个链表的 dummy = ListNode(0) dummy.next = head # python 新建一个链表,next指向 head
dummy = ListNode(0)
dummy.next = head
cur, length = head, 0
while cur:
length += 1
cur = cur.next
cur = dummy
for _ in range(length - n):
cur = cur.next
cur.next = cur.next.next
return dummy.next
参考的解法 包含了求链表的长度,直至这个指向None 很奇怪,这cur变化,dummy也随之变化 说明他们最终的存储是一样的,变化的只是引用 有考虑不设置cur ,直接用dummy,但是发现这个dummy是地址,每次都随之程序变化
弄明白了这个程序,然后自己设置了一个 自己设计的程序
dummy = ListNode(0)
dummy.next = head
cur, length = head, 0
while cur:
length += 1
cur = cur.next
cur=dummy
for i in range(length):
if i== (length-n):
cur.next=cur.next.next
else:
cur=cur.next
return dummy.next
解法大爆发 快慢指针
dummy = ListNode(0)
dummy.next = head
slow, fast = dummy, dummy
for _ in range(n):
fast = fast.next
while fast and fast.next:
slow, fast = slow.next, fast.next
slow.next = slow.next.next
return dummy.next
递归迭代(PASS:没看懂)
if not head:
self.count = 0
return head
head.next = self.removeNthFromEnd(head.next, n)
self.count += 1
return head.next if self.count == n else head
not用法
参考链接
|