Post condition If a node with key is found the linked list contains a new node

Post condition if a node with key is found the linked

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

// Post-condition: If a node with key is found, the linked list // contains a new node (newKey) after that node. void insert_after( Node* head, int key, int newKey ) { //please write your own code here Node * newNode = new Node; while (head != NULL){ if (head->key == key){ newNode->key = newKey;
Image of page 1
if (head->next == NULL){ head->next = newNode; newNode->next = NULL; } else { newNode->next = head->next; head->next = newNode; } break; } head = head->next; } } // This function merges two linked lists. // Pre-condition: Two linked lists (list1 and list2) are provided. // Post-condition: A new linked list is returned that contains the keys // of list1 and list2, starting with the first key of list1, then the // first key 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 ) { //please write your own code here to replace "return NULL" below Node * listNew; Node * temp; if (list1 == list2) return listNew = NULL; else if (list1 != NULL){ listNew = new Node; listNew->key = list1->key; list1 = list1->next; temp = listNew; } while (list1 !=NULL || list2 !=NULL){ if (list2 != NULL){ temp->next = new Node; temp->next->key = list2->key; list2 = list2->next; temp = temp->next; } if (list1 != NULL){ temp->next = new Node; temp->next->key = list1->key; list1 = list1->next; temp = temp->next; } } return listNew; } int main() { Node * list1 = NULL; Node * list2 = NULL; Node * list3 = NULL; Node * list4 = NULL; insert( list1, 1); insert( list1, 2); insert( list1, 3); std::cout << "<A> List 1: ";
Image of page 2
Image of page 3

You've reached the end of your free preview.

Want to read all 3 pages?

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture