leetcode刷题(单链表)7—删除链表的倒数第N个节点

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

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

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    
    
    //执行用时:0 ms, 在所有 Java 提交中击败了100.00%的用户
    //内存消耗:37.8 MB, 在所有 Java 提交中击败了79.85%的用户
    public ListNode removeNthFromEnd(ListNode head, int n) {
    
    
        int len = 0;
        ListNode p = head;
        while(p != null){
    
    
            ++len;
            p = p.next;
        }
        p = head;
        if(len == 0 || len == 1)
            return null;
        
        for(int i = 0; i < len - n - 1;++i){
    
    
            p = p.next;
        }
        //考虑首位删除问题
        if(len - n - 1 < 0)
            head = head.next;   
        else
            p.next = p.next.next;
        return head;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_38754625/article/details/108537526