收获:
1.在python中对链表中节点进行操作时:
a) 从前 我直接 return head (错误)
b)现在由于怕 head 会被修改,所以要设 point = Listnode(-1) return point
2. 我自己只想出了两遍遍历,收获了一遍遍历的思路: 双指针
a) 使 fast 与 slow 之间始终隔着 n,以例题为例,n=2,需要保证 fast = 5 时候 slow = 3 , slow.next = slow.next.next
b) 我记得之前学C的数据结构,需要借助middle 来传递 .next,like a = point.next; point.next = a.next; a.next = None
不知道在python 里面可以直接使用 slow.next = slow.next.next
代码1) 用了两次遍历的方法
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
tail = head
count = 0
while tail :
tail = tail.next
count +=1
print(n)
n = count - n
print(n)
if n ==0:
return head.next
else:
a = head
m = n-1
point = 0
while point < m:
head = head.next
point +=1
target = head.next
head.next = target.next
target.next = None
return a
代码2)一次遍历 思路借鉴leetcode官方题解
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
if head.next == None:
return None
point = ListNode(-1)
point.next = head
fast = slow = point
i = 0
while fast.next:
fast = fast.next
i+=1 # 2 3 4-2 5-3
if i>n:
slow = slow.next
slow.next = slow.next.next
return point.next
下图链接为