Construct a Maximum Sum Linked List out of two Sorted Linked Lists having some Common nodes
Given two sorted linked lists, construct a linked list that contains maximum sum path from start to end. The result list may contain nodes from both input lists. When constructing the result list, we may switch to the other input list only at the point of intersection (which mean the two node with the same value in the lists). You are allowed to use O(1) extra space.
List1 = 1->3->30->90->120->240->511
List2 = 0->3->12->32->90->125->240->249
Output: Following is maximum sum linked list out of two input lists
list = 1->3->12->32->90->125->240->511
we switch at 3 and 240 to get above maximum sum linked list
We strongly recommend to minimize the browser and try this yourself first.
The idea here in the below solution is to adjust next pointers after common nodes.
1. Start with head of both linked lists and find first common node. Use merging technique of sorted linked list for that.
2. Keep track of sum of the elements too while doing this and set head of result list based on greater sum till first common node.
3. After this till the current pointers of both lists don’t become NULL we need to adjust the next of prev pointers based on greater sum.
This way it can be done in-place with constant extra space.
Time complexity of the below solution is O(n).
// C++ program to construct the maximum sum linked
// list out of two given sorted lists
//A linked list node
intdata; //data belong to that node
Node *next; //next pointer
// Push the data to the head of the linked list
voidpush(Node **head, intdata)
//Alocation memory to the new node
Node *newnode = newNode;
//Assigning data to the new node
newnode->data = data;
//Adjusting next pointer of the new node
newnode->next = *head;
//New node becomes the head of the list
*head = newnode;
// Method that adjusts the pointers and prints the final list
voidfinalMaxSumList(Node *a, Node *b)
Node *result = NULL;
// Assigning pre and cur to the head of the
// linked list.
Node *pre1 = a, *curr1 = a;
Node *pre2 = b, *curr2 = b;
// Till either of the current pointers is not
// NULL execute the loop
while(curr1 != NULL || curr2 != NULL)
// Keeping 2 local variables at the start of every
// loop run to keep track of the sum between pre
// and cur pointer elements.
intsum1 = 0, sum2 = 0;
// Calculating sum by traversing the nodes of linked
// list as the merging of two linked list. The loop