leetcode_python_删除链表的倒数第N个节点

2021/6/1 20:24:12

本文主要是介绍leetcode_python_删除链表的倒数第N个节点,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

第一轮:

方法1:求长度,减去n得到被删除节点的前一个节点,直接跨越链接。若num=0则删除的是首节点

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next 
def LengthNode(self):
    length = 0
    while self:
        length += 1
        self = self.next
    return length 
class Solution:
  
    def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
        first = head
        length = LengthNode(head)
        num = length - n
        if num == 0:
            return first.next
        count = 1
        while count < num: 
            head = head.next
            # print(head.next.val)
            count += 1
        #找到被删节点的前一个节点 
        if head.next.next:
            head.next = head.next.next
        else:
            head.next = None
        return first

 



这篇关于leetcode_python_删除链表的倒数第N个节点的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程