当前位置:网站首页>[leetcode] 19. Delete the penultimate node of the linked list

[leetcode] 19. Delete the penultimate node of the linked list

2022-07-06 22:28:00 Xiaoqu classmate

19.、 Delete the last of the linked list N Nodes

subject :

I'll give you a list , Delete the last of the linked list n Nodes , And return the head node of the list .

Example 1:

 Input :head = [1,2,3,4,5], n = 2
 Output :[1,2,3,5]

Example 2:

 Input :head = [1], n = 1
 Output :[]

Example 3:

 Input :head = [1,2], n = 1
 Output :[1]

Tips :

The number of nodes in the list is sz
1 <= sz <= 30
0 <= Node.val <= 100
1 <= n <= sz

Their thinking :

This question LeetCode The difficulty of evaluation is medium , I think this question is simpler than the simple one .

Why do you say that ?

The linked list deletes a node at a certain position , Is it difficult ?

You can find rules . Because it is required to delete the penultimate n Nodes

The official solution is to calculate the length of the linked list 、 Stack and double pointer .

Here is a new idea , recursive ! Find the length of the deleted location linked list .

Simple and crude

Specific code :

/** * 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 {
    
        int i=0;
    public ListNode removeNthFromEnd(ListNode head, int n) {
    
             if(head.next!=null)
            head.next=removeNthFromEnd(head.next,n);
        i++;
        if(i==n)
            return head.next;
        else return head;
    }
}

 Insert picture description here

原网站

版权声明
本文为[Xiaoqu classmate]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/187/202207061447000827.html