|
| 1 | +/** |
| 2 | + Problem :-Remove the nth node from end of the list |
| 3 | + https://leetcode.com/problems/remove-nth-node-from-end-of-list/description/ |
| 4 | +
|
| 5 | + Approach:- |
| 6 | + 1. First find the length of the list and store it in a variable named 'len'. |
| 7 | + 2. Then traverse the list (len-n) |
| 8 | + 3. Now you are one node behind the node that we have to remove. |
| 9 | +
|
| 10 | + 4. Now set the current node's next to the next.next i.e temp.next=temp.next.next. |
| 11 | +
|
| 12 | + Time Complexity : O(N) |
| 13 | + we traverse the list for calculating its length and removing the node.Hence O(N). |
| 14 | +
|
| 15 | + Space Complexity : O(1) |
| 16 | + No extra space is required |
| 17 | +
|
| 18 | + Note :- The code is well documented. So take a look. |
| 19 | +
|
| 20 | +
|
| 21 | +
|
| 22 | + */ |
| 23 | + |
| 24 | + |
| 25 | +/** |
| 26 | + * Definition for singly-linked list. |
| 27 | + * public class ListNode { |
| 28 | + * int val; |
| 29 | + * ListNode next; |
| 30 | + * ListNode() {} |
| 31 | + * ListNode(int val) { this.val = val; } |
| 32 | + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } |
| 33 | + * } |
| 34 | + */ |
| 35 | + |
| 36 | +class Solution { |
| 37 | + public ListNode removeNthFromEnd(ListNode head, int n) { |
| 38 | + if (head == null) return head; // If the head is null, return the head itself |
| 39 | + if (head.next == null) { // If there is only one node in the list |
| 40 | + if (n == 1) return null; // If n is 1, remove the node and return null |
| 41 | + return head; // Otherwise, return the head itself |
| 42 | + } |
| 43 | + |
| 44 | + ListNode temp = head; // Create a temporary node pointing to the head |
| 45 | + |
| 46 | + int len = size(head); // Get the length of the list |
| 47 | + if (len - n == 0) { // If the node to be removed is the head itself |
| 48 | + head = head.next; // Move the head to the next node |
| 49 | + return head; |
| 50 | + } |
| 51 | + |
| 52 | + len -= n; // Calculate the index of the previous node of the node to be removed |
| 53 | + for (int i = 1; i < len; i++) { // Traverse to the previous node so we can remove the next node |
| 54 | + temp = temp.next; |
| 55 | + } |
| 56 | + |
| 57 | + if (temp != null && temp.next != null) { // If the previous node and the node to be removed exist |
| 58 | + temp.next = temp.next.next; // Point the previous node to the node after the one to be removed |
| 59 | + } |
| 60 | + |
| 61 | + return head; // Return the updated head |
| 62 | + } |
| 63 | + |
| 64 | + int size(ListNode temp) { |
| 65 | + ListNode s = temp; |
| 66 | + int n = 0; |
| 67 | + while (s != null) { // Traverse the list to count the number of nodes |
| 68 | + s = s.next; |
| 69 | + n += 1; |
| 70 | + } |
| 71 | + return n; // Return the size of the list |
| 72 | + } |
| 73 | +} |
0 commit comments