Remove Nth Node From End of List
Problem
Given the head
of a linked list, remove the nth
node from the end of the list and return its head.
Solution Approach
Click - to see solution code
- C++
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* t;
t = new ListNode;
t = head;
int cnt = 0;
while (t) {
cnt++;
t = t->next;
}
if (cnt == n) {
head = head->next;
return head;
}
n = cnt - n + 1;
int j = 1;
t = head;
while (j < n - 1) {
j++;
t = t->next;
}
t->next = t->next->next;
return head;
}
};