Tuesday, 5 October 2021

Remove Nth Node From End of List - LeetCode 19

 Given the head of a linked list, remove the nth node from the end of the list and return its head.

 

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]

 

Solution(Only function):

/**

 * 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 dummy_head=new ListNode(0);

        dummy_head.next=head;


        ListNode fast=dummy_head;

        ListNode slow=dummy_head;

        

        

        for(int i=1;i<=n+1;i++){

            fast=fast.next;

        }

        while(fast!=null){

            slow=slow.next;

            fast=fast.next;

        }

        slow.next=slow.next.next;

        return dummy_head.next;

    }

}

No comments:

Post a Comment

Random password generator in Java

       Random password generator in Java Source code: mport java.io.*; import java.util.*; public class Main { public static void main(Str...