Skip to content
This repository has been archived by the owner on Nov 3, 2024. It is now read-only.

Commit

Permalink
Remove Nth node from the end of list
Browse files Browse the repository at this point in the history
  • Loading branch information
Pranav Malhotra committed Oct 30, 2024
1 parent 5aefa58 commit fa30bd9
Show file tree
Hide file tree
Showing 3 changed files with 91 additions and 1 deletion.
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
#include <iostream>
using namespace std;

struct ListNode {
int val;
ListNode *next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode *next) : val(x), next(next) {}
};

class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
if (head == nullptr) {
return head;
}
ListNode* dummy = new ListNode(0, head);
ListNode* first = dummy;
ListNode* second = dummy;

for (int i = 0; i <= n; i++) {
first = first->next;
}

while (first != nullptr) {
first = first->next;
second = second->next;
}

ListNode* nodeToDelete = second->next;
second->next = nodeToDelete->next;
delete nodeToDelete;

ListNode* newHead = dummy->next;
delete dummy;
return newHead;
}
};

void printList(ListNode* head) {
ListNode* current = head;
while (current != nullptr) {
cout << current->val << " -> ";
current = current->next;
}
cout << "nullptr" << endl;
}

ListNode* createList(int arr[], int size) {
if (size == 0) return nullptr;
ListNode* head = new ListNode(arr[0]);
ListNode* current = head;
for (int i = 1; i < size; i++) {
current->next = new ListNode(arr[i]);
current = current->next;
}
return head;
}

int main() {
int arr[] = {1, 2, 3, 4, 5};
ListNode* head = createList(arr, 5);

cout << "Original List: ";
printList(head);

Solution solution;
int n = 2;
head = solution.removeNthFromEnd(head, n);

cout << "List after removing " << n << "th node from the end: ";
printList(head);

ListNode* temp;
while (head != nullptr) {
temp = head;
head = head->next;
delete temp;
}

return 0;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
Given the head of a linked list, remove the nth node from the end of the list and return its head.

Input: head = [1,2,3,4,5], n = 2
Output: [1,2,3,5]
5 changes: 4 additions & 1 deletion Beginner Level 📁/data.json
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,9 @@
"name": "Vimal M",
"githubUsername": "vimall03"
},

{
"name": "Pranav Malhotra",
"githubUsername": "Pranav-malhotra"
},
]

0 comments on commit fa30bd9

Please sign in to comment.