Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Please explain why the answer is what is is thoroughly. I am trying to study for

ID: 3827664 • Letter: P

Question

Please explain why the answer is what is is thoroughly. I am trying to study for my test. I will make sure to thumbs up! thank you very much for your time

struct node *move_last_to_first(struct node *list) {

struct node* prev, *cur;

if(list == NULL) return list; //the list is empty

for(prev = NULL, cur=list; cur->next !=NULL; prev = cur, cur = cur->next)

;

if(prev == NULL) //there is only one node in the list return list;

else{
prev ->next = NULL; cur ->next = list; return cur;

} }

18. Write the following function: struct node *move last to first(struct node *list); The list parameter points to a linked list of the following structure. struct node int value; struct node next The function should move the last node to be the head of the list, before the first node. The function should return a pointer to the head of the updated linked list.

Explanation / Answer

function should do following

if list is null then nothing can be moved, return NULL. (if(list == NULL) return list; //the list is empty)

If list has only one item, nothing can be done, return that item, (if(prev == NULL) //there is only one node in the list return list;)

Otherwise traverse to the last of the node, keeping pointer to last and second last node such that at end you have a node whose next is null and a node whose next is this node.

Now change next of last node to head an change next of last to last node to NULL.

This is what this code is doing

for(prev = NULL, cur=list; cur->next !=NULL; prev = cur, cur = cur->next)

;

This is going to end so that cur will be last node, prev is last to last node

prev ->next = NULL; removes link of last and second last node

cur ->next = list; will make cur is head and its next as head of list

and then return cur.