Question: There is an issue with my code. I need to write a program that creates a linked list and performs insertion, deleting from the beginning,
There is an issue with my code. I need to write a program that creates a linked list and performs insertion, deleting from the beginning, deleting from the end, and printing. Everything in the program works fine, but the delete the first node function. It throws an error in the printing function (posted a picture of the error below). Does anyone know what seems to be the problem? The function that deletes the last node works and prints perfectly.
LINKED LIST PROGRAM:
struct Node { int data; Node* next; };
void insert(Node** head,int n) //insertion method { Node* newNode = new Node; newNode->data = n; newNode->next = (*head); (*head) = newNode; }
Node* deleteFront(struct Node* head)//deleting first node in the list { if (head == NULL) return NULL; else { Node* t = head; head = head->next; free(t); t = NULL; } return head;
}
Node* deleteEnd(struct Node* head)//deleting last node in the list { if (head == NULL) return NULL; else if (head->next == NULL) { free(head); head = NULL; } else { Node* prev = head; Node* prev2 = head; while (prev->next != NULL) { prev2 = prev; prev = prev->next; } prev2->next = NULL; free(prev); prev = NULL; }
return head; } void printLL(Node* h) { while (h!=NULL) { cout data next; } cout
int main() { cout
deleteFront(n); cout
deleteEnd(n); cout
}
A picture of the error:


96 97 98 99 100 Node* prev2 = head; while (prev->next != NULL) { prev2 = prev; prev = prev->next; } prev2->next = NULL; free (prev); prev = NULL; 101 } 102 103 104 105 106 107 108 109 110 111 112 return head; } avoid printLL (Node* h) { while (h!=NULL) { cout data next; } cout
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
