jayati

Merge K sorted linked lists

Feb 20th, 2024
905
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.98 KB | None | 0 0
  1. class Solution{
  2.   public:
  3.     //Function to merge K sorted linked list.
  4.    Node* sortedMerge(Node* head1, Node* head2)  
  5. {  
  6.     // code here
  7.    if(head1==NULL) return head2;
  8.    if(head2==NULL) return head1;
  9.    
  10.    Node *head=NULL,*tail=NULL;
  11.    if(head1->data<=head2->data){
  12.        head=tail=head1;
  13.        head1=head1->next;
  14.    }else {
  15.        head=tail=head2;
  16.        head2=head2->next;
  17.    }
  18.    while(head1!=NULL && head2!=NULL){
  19.        if(head1->data<=head2->data){
  20.            tail->next=head1;
  21.            head1=head1->next;
  22.        }else {
  23.            tail->next=head2;
  24.            head2=head2->next;
  25.        }
  26.        tail=tail->next;
  27.    }
  28.    if(head1==NULL) tail->next=head2;
  29.    if(head2==NULL) tail->next=head1;
  30.    return head;
  31. }  
  32.     Node * mergeKLists(Node *arr[], int K)
  33.     {
  34.            // Your code here
  35.            Node *curr=arr[0];
  36.           for(int i=1;i<K;i++){
  37.                curr=sortedMerge(curr,arr[i]);
  38.           }
  39.            return curr;
  40.     }
  41. };
  42.  
Advertisement
Add Comment
Please, Sign In to add comment