题目:
思路:
以示例为为例,指针遍历到“3”是用一个temp指针代之其,然后遍历到要删除的“4”位置,将这个位置的next,赋值给temp.next,这样就删去了这个指针。
代码:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
now_point = head
num = 0
while now_point!=None: //遍历整个链表,查询链表长度,用num记录
now_point = now_point.next
num +=1
if num ==1 and n ==1: //如果链表长度为1,n为1就返回None
return None
k = num -n //被删链表节点
j = 0
now_point = head
if k == 0:
head = head.next
for _ in range(k):
if j == k-1:
temp = now_point //被删节点前一个节点,用temp指针指向
now_point = now_point.next //遍历到下一个节点
j +=1
if j ==k:
temp.next = now_point.next //如果这个节点是要删掉的节点,将其next赋值给temp.next
return head //返回头部