Programming Fundamentals
Download list_delete_second_last.c here
Or, copy these file(s) to your CSE account using the following command:
1511 fetch-activity list_delete_second_last
Your task is to add code to this function in list_delete_second_last.c:
//
// Delete the second last node in the list.
// The deleted node is freed.
// The head of the list is returned.
//
struct node *delete_second_last(struct node *head) {
// PUT YOUR CODE HERE (change the next line!)
return NULL;
}
Note list_delete_second_last.c uses the following familiar data type:
struct node {
struct node *next;
int data;
};
delete_second_last is given one argument, head, which is the pointer to the
first node in a linked list.
Add code to delete_second_last so that it deletes the second last node from
list.
delete_second_last should return a pointer to the new list.
If the list is empty, delete_second_last should return NULL.
If the list has exactly one element, delete_second_last should return that
one element unchanged.
delete_second_last should call free to free the memory of the node it
deletes.
For example if the linked list contains these 8 elements:
16, 7, 8, 12, 13, 19, 21, 12
delete_second_last should return a pointer to a list with these elements:
16, 7, 8, 12, 13, 19, 12
Testing
list_delete_second_last.c also contains a main function which allows you to
test your delete_second_last function.
This main function:
- converts the command-line arguments to a linked list
- assigns a pointer to the first node in the linked list to
head - calls
delete_second_last(head) - prints the result.
Do not change this main function. If you want to change it, you have misread the question.
Your delete_second_last function will be called directly in marking.
The main function is only to let you test your delete_second_last function
Examples
dcc list_delete_second_last.c -o list_delete_second_last ./list_delete_second_last 16 7 8 12 13 19 21 12 [16, 7, 8, 12, 13, 19, 12] ./list_delete_second_last 2 4 6 2 4 6 [2, 4, 6, 2, 6] ./list_delete_second_last 42 [42] ./list_delete_second_last []
Assumptions/Restrictions/Clarifications
delete_second_lastshould callfreeto free the memory for the node it deletesdelete_second_lastshould not change the data fields of list nodes.delete_second_lastshould not use arrays.delete_second_lastshould not call malloc.delete_second_lastshould not callscanf(orgetcharorfgets).delete_second_lastshould not print anything. It should not callprintf.- Do not change the supplied
mainfunction. It will not be tested or marked.