I'm working on 19. Remove Nth Node From End Of List on LeetCode. I thought it would be pretty simple:
struct ListNode* removeNthFromEnd(struct ListNode* head, int n){
int count = 1;
struct ListNode* curr_node = head;
while (curr_node->next) {
curr_node = curr_node->next;
count ;
}
int forward = count-n;
count = 0;
curr_node = head;
while (count < forward) {
curr_node = curr_node->next;
count ;
}
struct ListNode * next_node = curr_node->next;
struct ListNode final_before = *curr_node;
final_before.next = next_node->next;
return head;
}
but the above code fails to modify the list connected to the 'head' node they pass me at all. Is there a way to take a linked list in C and modify it 'in place'?
CodePudding user response:
Your problem is here:
struct ListNode final_before = *curr_node;
Note that in the line above, you've created a new struct ListNode
object that is a local variable of your function, and set it to be a copy of the ListNode
that curr_node
is currently pointing to.
final_before.next = next_node->next;
return head;
... then on the next line you modify final_before
, and right after that you return from the function, and so your local-variable final_before
gets discarded along with your modification to it. That's why your function has no effect on the linked list.
The easy fix would be to be to remove the lines involving final_before
entirely, and instead just write:
curr_node->next = next_node->next;
(Since curr_node
is pointing to a ListNode that is actually part of the linked list and not to a local variable, this change will be seen by latter users of the linked list)