The following function exchanges the first node in the list with the second node and returns a pointer to the front of the edited list. If the original list contains fewer than two nodes, no changes are made, and the original pointer to the front of the list will be returned.
This function was written by a professor, but I am having trouble understanding why he sets
list->next = newFront->next.
I understand that he creates a new pointer to equal the address of the second node and the next of that newly created pointer will equal the address of the first node but why is it necessary to set the address of the second node in the original list equal to newFront->next: list->next = newFront->next. Is this step even necessary?
Here is the entire code:
struct node {
int data;
struct node *next;
};
struct node* swapFirstTwo(struct node* list) {
if(list == NULL || list->next == NULL) return list;
struct node* newFront = list->next;
list->next = newFront->next;
newFront->next = list;
return newFront;
}