
给你一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点。
示例 1:
输入:head = [1,2,3,4,5], n = 2 输出:[1,2,3,5]
示例 2:
输入:head = [1], n = 1 输出:[]
示例 3:
输入:head = [1,2], n = 1 输出:[1]
class Solution {
public ListNode removeNthFromEnd(ListNode head,int n){
int pos=length(head, n);
if(pos==n)
return head.next;
return head;
}
public int length(ListNode node,int n){
if(node==null) return 0;
int pos=length(node.next,n)+1;
if(pos==n+1)
node.next=node.next.next;
return pos;
}
}
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode pre=head;
int last=length(head)-n;
if(last==0) return head.next;
for(int i=0;i
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)