【leetcode每日一题】【2019-06-19】19. 删除链表的倒数第N个节点

博客围绕删除链表的倒数第N个节点展开,给出了题目地址https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/submissions/,并介绍思路是将该位置前一个List的Next指向其下一个数字,还提及有Python和Scala代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

地址: https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/submissions/

给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。

示例:

给定一个链表: 1->2->3->4->5, 和 n = 2.

当删除了倒数第二个节点后,链表变为 1->2->3->5.
说明:

给定的 n 保证是有效的。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路就是把这个位置的数字前一个List的Next指向这个位置的下一个数字

Python代码:

# 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:
        tmp=[]
        current=head
        while current != None:
            tmp.append(current)
            current=current.next
        if n==1:
            if len(tmp)==1:
                tmp[0] = []
            else:
                tmp[len(tmp)-1-1].next=None
        else:
            if len(tmp)-n-1<0:
                tmp[0]=tmp[1]
            else:
                tmp[len(tmp)-n-1].next=tmp[len(tmp)-n+1]
        return tmp[0]

Scala代码:

/**
 * Definition for singly-linked list.
 * class ListNode(var _x: Int = 0) {
 *   var next: ListNode = null
 *   var x: Int = _x
 * }
 */
object Solution {
    def removeNthFromEnd(head: ListNode, n: Int): ListNode = {
        var tmp=scala.collection.mutable.ArrayBuffer[ListNode]()
        var current=head
        while (current != null){
          tmp.append(current)
          current=current.next 
        }
        if (n==1){
            if (tmp.length==1){
                tmp(0)=null
            }else{
                tmp(tmp.length-1-1).next=null
            }
        }else{
            if (tmp.length-n-1<0){
                tmp(0)=tmp(1)
            }else{
                tmp(tmp.length-n-1).next=tmp(tmp.length-n+1)
            }
        }
        return tmp(0)
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值