LeetCode19. Remove Nth Node From End of List

题目: Given a linked list, remove the n -th node from the end of list and return its head.
代码:
# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def removeNthFromEnd(self, head, n):
        """
        :type head: ListNode
        :type n: int
        :rtype: ListNode
        """
        i=1
        node = head
        while node.next:
            i+=1
            node=node.next

        if i-n==0:
            if head.next:
                nxt=head.next
                del(head)
                head = nxt
            else:
                head=None
            return head    

        j=1
        node=head
        while j<i-n:
            node=node.next
            j+=1
        nxt=node.next         
               
        node.next=nxt.next
        del(nxt)
        return head

解释:该题是根据给出的数字n删除链表倒数第n个元素。
解题时首先计算出了链表共有i个元素,倒数第n个元素的前一个元素为第i-n个元素node,如果i-n为0,则删除的是第一个元素,需要将头指针指向下一各元素,同时,如果只有一个元素则头元素为空。否则删除的元素为第i-n+1个元素nxt,node的下一个指针指向nxt所指向的。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值