【JAVA】删除链表的倒数第N个节点

  • Post author:
  • Post category:java


给你一个链表,删除链表的倒数第

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]
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
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;
    }
}
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
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<last-1;i++) pre=pre.next;

        pre.next=pre.next.next;
        return head;
    }

    private int length(ListNode head) {
        int len=0;
        while(head!=null) {
            len++;
            head=head.next;
        }
        return len;
    }
}



版权声明:本文为qq_42615233原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。