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)
}
}