Function to delete the last element of this linked list?? struct Node{ int data;
ID: 3763143 • Letter: F
Question
Function to delete the last element of this linked list??
struct Node{
int data;
struct Node* next;
};
typedef struct Node Node;
typedef struct List{
Node* head;
}List;
List makeEmptyList(){
List ret;
ret.head = NULL;
return ret;
}
void prependToList(List* l, int data){
Node* n = malloc(sizeof(Node));
n->data = data;
n->next = l->head;
l->head = n;
}
void printList(List l){
for(Node* cursor = l.head; cursor != NULL; cursor = cursor->next){
printf("%d ", cursor->data);
}
}
int main(){
List l = makeEmptyList();
for(int i = 0; i < 5; i++){
prependToList(&l, i);
}
printList(l);
return 0;
}
Explanation / Answer
void deleteLast(List l){
Node *cursor,*indicator;
cursor = l.head;
while (cursor->next!=NULL)
{
indicator=cursor;
cursor = cursor->next;
}
free(indicator->next);
indicator->next = NULL;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.