力扣第19题“删除链表的倒数第N个节点”(python解决)

题目:

思路:

以示例为为例,指针遍历到“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  //返回头部

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值