Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution{
- public:
- //Function to merge K sorted linked list.
- Node* sortedMerge(Node* head1, Node* head2)
- {
- // code here
- if(head1==NULL) return head2;
- if(head2==NULL) return head1;
- Node *head=NULL,*tail=NULL;
- if(head1->data<=head2->data){
- head=tail=head1;
- head1=head1->next;
- }else {
- head=tail=head2;
- head2=head2->next;
- }
- while(head1!=NULL && head2!=NULL){
- if(head1->data<=head2->data){
- tail->next=head1;
- head1=head1->next;
- }else {
- tail->next=head2;
- head2=head2->next;
- }
- tail=tail->next;
- }
- if(head1==NULL) tail->next=head2;
- if(head2==NULL) tail->next=head1;
- return head;
- }
- Node * mergeKLists(Node *arr[], int K)
- {
- // Your code here
- Node *curr=arr[0];
- for(int i=1;i<K;i++){
- curr=sortedMerge(curr,arr[i]);
- }
- return curr;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment