Answers for "merge two sorted linked lists"

C++
1

merge two sorted linked lists

// Complete soultion by me
//I will request to try this on your own first
#include<iostream>
using namespace std;
struct node
{
  int data;
  node* next;
};
node* head=NULL;
node * head1=NULL;
node* headbed=NULL;
void insertion(node **head2 ,int key)
{
  node * temp=new node;
  temp->data=key;
  temp->next=NULL;
  if(*head2==NULL)
  {
    *head2=temp;
  }
  else
  {
    node * ptr=*head2;
    while(ptr->next!=NULL)
    {
      ptr=ptr->next;
    }
    ptr->next=temp;
  }
}
void merge()
{
  node *ptr=head;
  node * str=head1;
  while(ptr!=NULL&&str!=NULL)
  {
    if((ptr->data)<(str->data))
    {
      insertion(&headbed,ptr->data);
      ptr=ptr->next;
    }
    else
    {
      insertion(&headbed,(str->data));
      str=str->next;
    }
  }
  while(ptr!=NULL)
  {
    insertion(&headbed,ptr->data);
      ptr=ptr->next;
  }
  while(str!=NULL)
  {
    insertion(&headbed,str->data);
    str=str->next;
  }
}
void print(node *heads)
{
  node* temp=heads;
  while(temp!=NULL)
  {
    cout<<temp->data<<"->";
    temp=temp->next;
  }
  cout<<"NULL";
}
int main()
{
  int n;
  cin>>n;
  int value;
  for(int i=0;i<n;i++)
  {
   cin>>value;
    insertion(&head,value);
  }
  int n2;
  cin>>n2;
  for(int i=0;i<n2;i++)
  {
    cin>>value;
    insertion(&head1,value);
  }
  merge();
  print(headbed);
  return 0;
}
Posted by: Guest on July-25-2021
0

merge sort in linked list

Merge_Sort(head_reference)

STEP 1: If head is NULL or there is only one element in the Linked List 
    then return the Linked List
    
STEP 2: Divide the linked list into two equal halves.  
      Split_Linked_List(head, &first_half, &second_half);
      
STEP 3: Sort the two halves first_half and second_half.
      MergeSort(first_half);
      MergeSort(second_half);
      
STEP 4: Merge the sorted first_half and second_half (using Merge_Sort() recursively) 
   and update the head pointer using head_reference.
     *head_reference = Merge_Sort(first_half, second_half);
Posted by: Guest on September-29-2020

Browse Popular Code Answers by Language