Trouble with single linked list
So I was doing the removing node for single linked list, I made 3 functions but somehow it created infinite data although it deletes the data I need. Here is my code:
Node delHead(Node head){
if(head==NULL){
printf("There is nothing to delete!");
}
else{
head=head->next;
}
return head;
}
Node delTail(Node head){
if(head==NULL||head->next==NULL){
return delHead(head);
}else{
Node p = head;
Node prev = NULL;
while(p->next !=NULL){
prev=p;
p=p->next;
}
prev->next= NULL;
free(p);
return head;
}
}
Node delAt(Node head, int position){
if(position == 0 || head == NULL || head->next == NULL){
head = delHead(head);
}else{
int k = 0;
Node p = head;
Node prev = NULL;
while(p != NULL && k != position){
prev = p;
p=p->next;
k++;
}
if(k != position){
head = delTail(head);
}else{
prev->next=p->next;
free(p);
}
}
return head;
}
I’m using visual studio code, so I hope someone can fix me with this. I try p->next->next but it didn’t work out so appreciate you guys so much. Thank you!
2
Answers
There seems to be an issue with your code in the
delAt
function. The problem lies in the conditionif (k != position)
. This condition checks whether the loop terminated becausek
reached the desiredposition
. However, the loop could also terminate ifp
becomesNULL
before reaching the desired position. In that case, you should delete the tail instead of the node at the specified position.To fix this issue, you can modify the
delAt
function as follows:In the modified code, the condition
if (p == NULL)
is used to check if the loop terminated becausep
becameNULL
. In that case, we delete the tail of the list using thedelTail
function.I hope this helps to resolve the issue you were facing.
As mentioned in another comment, you should have provided an example of how you code and the output it gave you. I only noticed 1 issue, you were using a Node instead of a Node* for your paramaters, return values, and local variables. I changed the code and validated that your original functions were correct.
Output: