C++ I have a small question in this piece of code. I wanna add that if a positio
ID: 3866731 • Letter: C
Question
C++ I have a small question in this piece of code. I wanna add that if a position is not found return -1; & if we reach the end of the list or node not found. Please if you do not know don't answer it. and no it is not as simple as:
ListNode *n = head;
if (n == NULL) return -1; //This would be wrong!!!!!!!!!!! and totally wrong so please chegg answerers don't answer if you do not know
int NumberList::removeByPosition(int position)
{
ListNode *n = head;
if (n == NULL) return;
while (position > 0 && n)
{
n = n->next;
position--;
}
if (n == head)
{
head = head->next;
delete n;
return;
}
else
{
if (n == NULL) return;
ListNode *rear = head;
while (rear->next != n)
rear = rear->next;
rear->next = n->next;
delete n;
}
}
Explanation / Answer
I will Provide whole running code
#include <bits/stdc++.h>
using namespace std;
struct ListNode
{
int data;
struct ListNode *next;
};
void push(struct ListNode** head, int new_data)
{
struct ListNode* new_node = (struct ListNode*) malloc(sizeof(struct ListNode));
new_node->data = new_data;
new_node->next = (*head);
(*head) = new_node;
}
void removeByPosition(struct ListNode **head, int position)
{
int k=1;
if (*head == NULL)
return;
struct ListNode* p, *q;
p= *head;
if(position==1){
*head=(*head)->next;
free(p);
return ;
}
else{
while( p!=NULL && k<position)
{
k++;
q=p;
p=p->next;
}
if(p==NULL)
{
printf("Postion does not exist");
return ;
}
else{
q->next=p->next;
free(p);
}
}
}
void printList(struct ListNode *node)
{
while (node != NULL)
{
printf(" %d ", node->data);
node = node->next;
}
}
int main()
{
struct ListNode* head = NULL;
push(&head, 7);
push(&head, 1);
push(&head, 3);
push(&head, 2);
push(&head, 8);
puts("Created Linked List: ");
printList(head);
removeByPosition(&head, 4);
puts(" Linked List after Deletion at position 4: ");
printList(head);
return 0;
}
int NumberList::removeByPosition(ListNode **head,int position)
{
int k=1;
ListNode *p,*q;
if(*head==NULL)
return -1;
p=*head;
if(position==1){
*head=(*head)->next;
free(p);
return ;
}
else{
while( p!=NULL && k<position)
{
k++;
q=p;
p=p->next;
}
if(p==NULL)
{
cout<<"Postion does not exist";
return -1;
}
else{
q->next=p->next;
free(p);
}
}
}
If you like this answer , then please Like
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.