13.07.2015 Views

Linked List Problems

Linked List Problems

Linked List Problems

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

203 — Delete<strong>List</strong>() SolutionDelete the whole list and set the head pointer to NULL. Slight complication in the insideof the loop, since we need extract the .next pointer before we delete the node, sinceafter the delete it will be technically unavailable.void Delete<strong>List</strong>(struct node** headRef) {struct node* current = *headRef; // deref headRef to get the real headstruct node* next;while (current != NULL) {next = current->next;free(current);current = next;}// note the next pointer// delete the node// advance to the next node}*headRef = NULL;// Again, deref headRef to affect the real head back// in the caller.4 — Pop() SolutionExtract the data from the head node, delete the node, advance the head pointer to point atthe next node in line. Uses a reference parameter since it changes the head pointer.int Pop(struct node** headRef) {struct node* head;int result;head = *headRef;assert(head != NULL);result = head->data; // pull out the data before the node is deleted*headRef = head->next; // unlink the head node for the caller (// Note the * -- uses a reference-pointer// just like Push() and Delete<strong>List</strong>().}free(head);return(result);// free the head node// don't forget to return the data from the link5 — InsertNth() SolutionThis code handles inserting at the very front as a special case. Otherwise, it works byrunning a current pointer to the node before where the new node should go. Uses a forloop to march the pointer forward. The exact bounds of the loop (the use of < vs

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!