head NULL delete head head n else if head next key oldKey Node n head next head

Head null delete head head n else if head next key

This preview shows page 2 - 3 out of 3 pages.

head = NULL; delete head; head = n; } else if (head->next->key == oldKey) { Node* n = head->next; head->next = head->next->next; delete n; } else { remove(head->next, oldKey); } } } /** * Insert a new Node (with key=newKey) after an existing Node (with key=oldKey) * If there is no existing Node with key=oldKey, then no action. * PRE: head is the first Node in a linked_list (if NULL, linked_list is empty) * PRE: oldKey is the value to look for (in the key of an existing Node) * PRE: newKey is the value of the key in the new Node (that might be inserted) * POST: if no Node with key=oldKey was found, then the linked_list has not changed * POST: else a new Node (with key=newKey) is right after the Node with key = oldKey. */ void insert_after(Node* head, int oldKey, int newKey){ if (head != NULL) { if (head->key == oldKey) { Node* n = new Node; n->key = newKey; n->next = head->next; head->next = n; } else { insert_after(head->next, oldKey, newKey); } } } /** * Create a new linked_list by merging two existing linked_lists. * PRE: list1 is the first Node in a linked_list (if NULL, then it is empty) * PRE: list2 is the first Node in another linked_list (if NULL, then it is empty) * POST: A new linked_list is returned that contains new Nodes with the keys
Image of page 2
from * the Nodes in list1 and list2, starting with the key of the first Node of list1, * then the key of the first Node of list2, etc. * When one list is exhausted, the remaining keys come from the other list. * For example: [1, 2] and [3, 4, 5] would return [1, 3, 2, 4, 5] */ Node* interleave(Node* list1, Node* list2){ Node* head = NULL; Node* curr = head; while(list1 && list2) { Node* n1 = new Node; Node* n2 = new Node; n1->key = list1->key; n2->key = list2->key; n1->next = n2; n2->next = NULL; if(!head) { head = n1; } else { curr->next = n1; } curr = n2; list1 = list1->next; list2 = list2->next; } while(list2) { Node* n2 = new Node; n2->key = list2->key; n2->next = NULL; if(!head) { head = n2; curr = head; } else { curr->next = n2; curr = curr->next; } list2 = list2->next; } while(list1) { Node* n1 = new Node; n1->key = list1->key; n1->next = NULL; if(!head) { head = n1; curr = head; } else { curr->next = n1; curr = curr->next; } list1 = list1->next; } return head; }
Image of page 3

You've reached the end of your free preview.

Want to read all 3 pages?

  • Fall '17
  • AbdullahAtalar
  • The Key, #include, new node, list lab

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture