SlideShare a Scribd company logo
Write a function to merge two doubly linked lists. The input lists have their elements in sorted
order, from lowest to highest. The output list should also be sorted from lowest to highest. Your
algorithm should run in linear time on the length of the output list. Provide an algorithm for your
function Implement and show some samples of your running function
Solution
The algorithm for LinkedList MergeSort is as follows.
The trick in this algorithm is to use a local list to store the value which is pointing to the actual
list to be returned as a result of the function
Step1: START
Step2: GET inputs of list1 and list2
Step3: INITIALIZE mergelist
STEP4: SET mylist = mergelist
Step5: WHILE list1 OR list2 is EMPTY
DO
IF (list1 AND list2) are NOT EMPTY
IF list1.value > list2.value
mylist.next = list2
ELSE
mylist.next = list1
ELSE IF list1 is EMPTY
mylist.next = list2
ELSE
mylist.next = list1
Step6: RETURN mergelist
Step7: STOP
Sample program for the same implemented in C++
//====================================================================
========
// Name : DoublyLinkedList.cpp
// Author : Kaju
// Version : 0.1
// Copyright : This is just an example code
// Description : MergeSort in C++, Ansi-style
//====================================================================
========
/*
* C++ Program to Implement Doubly Linked List
*/
#include
#include
#include
/*
* Node Declaration
*/
using namespace std;
// struct declaration for node which will hold the integer data with links to previous data and next
data
struct node
{
int data;
struct node *next;
struct node *prev;
};
/*
Class Declaration
*/
class DoublyLinkedList
{
private:
struct node *start; // collection of all the nodes
public:
void create(int value);
int peek();
int delete_head();
void display();
int count();
void mergeSort(DoublyLinkedList list1, DoublyLinkedList list2);
DoublyLinkedList()
{
start = NULL;
}
};
/*
* Add data into the list
*/
void DoublyLinkedList::create(int value)
{
struct node *s, *temp;
temp = new(struct node);
temp->data = value;
temp->next = NULL;
if (start == NULL)
{
temp->prev = NULL;
start = temp;
}
else
{
s = start;
while (s->next != NULL)
s = s->next;
s->next = temp;
temp->prev = s;
}
}
/*
* Deletion of the first element from the list
* store the first element in a temp node and then remove it from start.
*/
int DoublyLinkedList::delete_head()
{
struct node *tmp, *q;
int value;
tmp = start;
if(start->next!=NULL)
{
start = start->next;
start->prev = NULL;
}
else
start = NULL;
value = tmp->data;
free(tmp);
return value;
}
/*
* return the first element of Doubly Link List
*/
int DoublyLinkedList::peek()
{
struct node *q;
if (start == NULL)
{
cout<<"List is empty"<data;
}
}
/*
* Display elements of Doubly Link List
*/
void DoublyLinkedList::display()
{
struct node *q;
if (start == NULL)
{
cout<<"List is empty"<data;
q = q->next;
if(q != NULL)
{
cout<<", ";
}
}
cout<<"]"<next;
cnt++;
}
return cnt;
}
/*
* MergeSort - takes two input lists and then based on the integer data value sorts them in
ascending order.
* Adds each data removed from the input lists into the new list.
*/
void DoublyLinkedList::mergeSort(DoublyLinkedList list1, DoublyLinkedList list2)
{
while(list1.count() > 0 || list2.count() > 0) // Checks whether any of the list is empty
{
if(list1.count() > 0 && list2.count() > 0) // checks if both the lists have data
{
if(list1.peek() > list2.peek()) // compares the first element of both the lists
create(list2.delete_head()); // if the second list has greater value then it is removed from the
second list and added to the new list
else
create(list1.delete_head());// if the first list has greater value then it is removed from the first list
and added to the new list
}
else if(list1.count() == 0) // incase where list one is empty and only list two has value
{
create(list2.delete_head()); // if the second list has value then it is removed from the second list
and added to the new list
}
else
{
create(list1.delete_head()); // if the first list has value then it is removed from the first list and
added to the new list
}
}
}
int main()
{
DoublyLinkedList firstList;
firstList.create(4);
firstList.create(10);
firstList.create(45);
firstList.create(53);
firstList.create(250);
firstList.create(1020);
cout<<"List 1: ";
firstList.display();
DoublyLinkedList secondList;
secondList.create(1);
secondList.create(36);
secondList.create(68);
secondList.create(73);
secondList.create(1019);
cout<<"List 2: ";
secondList.display();
DoublyLinkedList mergedList;
mergedList.mergeSort(firstList, secondList);
cout<<"Merged List: ";
mergedList.display();
return 0;
}
OUTPUT:
List 1: [4, 10, 45, 53, 250, 1020]
List 2: [1, 36, 78, 673, 1019]
Merged List: [1, 4, 10, 36, 45, 53, 78, 250, 673, 1019, 1020]

More Related Content

Similar to Write a function to merge two doubly linked lists. The input lists ha.pdf (20)

PDF
Data Structures in C++I am really new to C++, so links are really .pdf
rohit219406
 
PDF
In C++Write a recursive function to determine whether or not a Lin.pdf
flashfashioncasualwe
 
PDF
Implement a priority queue using a doublyLinked-cpp where the node wit.pdf
BlakeY8lBucklandh
 
PPTX
Linear data structure concepts
Akila Krishnamoorthy
 
PDF
Need to be done in C++ Please Sorted number list implementation wit.pdf
aathiauto
 
PDF
implement the ListLinked ADT (the declaration is given in ListLinked.pdf
FOREVERPRODUCTCHD
 
PDF
This assignment and the next (#5) involve design and development of a.pdf
EricvtJFraserr
 
PDF
Inspect the class declaration for a doubly-linked list node in Node-h-.pdf
vishalateen
 
PDF
Need to be done in C Please Sorted number list implementation with.pdf
aathmaproducts
 
PDF
Need done for Date Structures please! 4-18 LAB- Sorted number list imp.pdf
info114
 
PPTX
data structure3.pptx
SajalFayyaz
 
PDF
In the class we extensively discussed a node class called IntNode in.pdf
arjunstores123
 
DOCX
Doubly linklist
ilsamaryum
 
PDF
Merge Sort implementation in C++ The implementation for Mergesort gi.pdf
mdameer02
 
DOCX
Linked lists
George Scott IV
 
PDF
Write a program to implement below operations with both singly and d.pdf
thangarajarivukadal
 
PDF
Complete a C++ class implementation for a linked-list of sorted (asc.pdf
shahidqamar17
 
PDF
Complete the provided partial C++ Linked List program. Main.cpp is g.pdf
rajkumarm401
 
DOCX
C++ help! Write a function merge that merges two lists into one- alter.docx
gilliandunce53776
 
PDF
C++ Program to Implement Doubly Linked List #includei.pdf
Lalkamal2
 
Data Structures in C++I am really new to C++, so links are really .pdf
rohit219406
 
In C++Write a recursive function to determine whether or not a Lin.pdf
flashfashioncasualwe
 
Implement a priority queue using a doublyLinked-cpp where the node wit.pdf
BlakeY8lBucklandh
 
Linear data structure concepts
Akila Krishnamoorthy
 
Need to be done in C++ Please Sorted number list implementation wit.pdf
aathiauto
 
implement the ListLinked ADT (the declaration is given in ListLinked.pdf
FOREVERPRODUCTCHD
 
This assignment and the next (#5) involve design and development of a.pdf
EricvtJFraserr
 
Inspect the class declaration for a doubly-linked list node in Node-h-.pdf
vishalateen
 
Need to be done in C Please Sorted number list implementation with.pdf
aathmaproducts
 
Need done for Date Structures please! 4-18 LAB- Sorted number list imp.pdf
info114
 
data structure3.pptx
SajalFayyaz
 
In the class we extensively discussed a node class called IntNode in.pdf
arjunstores123
 
Doubly linklist
ilsamaryum
 
Merge Sort implementation in C++ The implementation for Mergesort gi.pdf
mdameer02
 
Linked lists
George Scott IV
 
Write a program to implement below operations with both singly and d.pdf
thangarajarivukadal
 
Complete a C++ class implementation for a linked-list of sorted (asc.pdf
shahidqamar17
 
Complete the provided partial C++ Linked List program. Main.cpp is g.pdf
rajkumarm401
 
C++ help! Write a function merge that merges two lists into one- alter.docx
gilliandunce53776
 
C++ Program to Implement Doubly Linked List #includei.pdf
Lalkamal2
 

More from info706022 (20)

PDF
Many biologists will talk about the group known as Ungulates, or hoo.pdf
info706022
 
PDF
Match the function with the appropriate organelle in the column at ri.pdf
info706022
 
PDF
It costs $16 to travel in a specific zone in paris. Now suppose thei.pdf
info706022
 
PDF
Let X and Y be two random variables whose joint probability density .pdf
info706022
 
PDF
Identify whether the Fed should continue its current pace of securit.pdf
info706022
 
PDF
If 2 and z are incompletely dominant, how many different phenotypes a.pdf
info706022
 
PDF
How are criminals maximizing their total utilitySolutionThe o.pdf
info706022
 
PDF
How do I change this javascript code so that the new page opens up b.pdf
info706022
 
PDF
Help with my biostats Homework. Please show all work!! Mendel develo.pdf
info706022
 
PDF
genetics q If the offspring of a dihydric testcross are roughly 50 .pdf
info706022
 
PDF
for fiscal year 2006, the national debt of a country was approximate.pdf
info706022
 
PDF
Explain why Linux makes system performance monitoring available to t.pdf
info706022
 
PDF
Discuss the relationships between competitive avantage, istinctive c.pdf
info706022
 
PDF
Determine the intervals of the domain over which each function is.pdf
info706022
 
PDF
A storage reservoir contains 200 kg of a liquid that has a specific .pdf
info706022
 
PDF
4. Define modal split model transportation demand . central vision .pdf
info706022
 
PDF
Comparison of dysplasia and hyperplasiaSolutionDysplasia Dys.pdf
info706022
 
PDF
“Web 2.0 is simply a new label for a range of web technologies and c.pdf
info706022
 
PDF
You are required, but not limited, to turn in the following source f.pdf
info706022
 
PDF
Why just one sperm can enter the secondary oocyteWhy just one s.pdf
info706022
 
Many biologists will talk about the group known as Ungulates, or hoo.pdf
info706022
 
Match the function with the appropriate organelle in the column at ri.pdf
info706022
 
It costs $16 to travel in a specific zone in paris. Now suppose thei.pdf
info706022
 
Let X and Y be two random variables whose joint probability density .pdf
info706022
 
Identify whether the Fed should continue its current pace of securit.pdf
info706022
 
If 2 and z are incompletely dominant, how many different phenotypes a.pdf
info706022
 
How are criminals maximizing their total utilitySolutionThe o.pdf
info706022
 
How do I change this javascript code so that the new page opens up b.pdf
info706022
 
Help with my biostats Homework. Please show all work!! Mendel develo.pdf
info706022
 
genetics q If the offspring of a dihydric testcross are roughly 50 .pdf
info706022
 
for fiscal year 2006, the national debt of a country was approximate.pdf
info706022
 
Explain why Linux makes system performance monitoring available to t.pdf
info706022
 
Discuss the relationships between competitive avantage, istinctive c.pdf
info706022
 
Determine the intervals of the domain over which each function is.pdf
info706022
 
A storage reservoir contains 200 kg of a liquid that has a specific .pdf
info706022
 
4. Define modal split model transportation demand . central vision .pdf
info706022
 
Comparison of dysplasia and hyperplasiaSolutionDysplasia Dys.pdf
info706022
 
“Web 2.0 is simply a new label for a range of web technologies and c.pdf
info706022
 
You are required, but not limited, to turn in the following source f.pdf
info706022
 
Why just one sperm can enter the secondary oocyteWhy just one s.pdf
info706022
 
Ad

Recently uploaded (20)

PPTX
How to Create Odoo JS Dialog_Popup in Odoo 18
Celine George
 
PDF
Reconstruct, Restore, Reimagine: New Perspectives on Stoke Newington’s Histor...
History of Stoke Newington
 
PPTX
I AM MALALA The Girl Who Stood Up for Education and was Shot by the Taliban...
Beena E S
 
PDF
DIGESTION OF CARBOHYDRATES,PROTEINS,LIPIDS
raviralanaresh2
 
PDF
Biological Bilingual Glossary Hindi and English Medium
World of Wisdom
 
PDF
Dimensions of Societal Planning in Commonism
StefanMz
 
PDF
CONCURSO DE POESIA “POETUFAS – PASSOS SUAVES PELO VERSO.pdf
Colégio Santa Teresinha
 
PPTX
CATEGORIES OF NURSING PERSONNEL: HOSPITAL & COLLEGE
PRADEEP ABOTHU
 
PPTX
Growth and development and milestones, factors
BHUVANESHWARI BADIGER
 
PPTX
QUARTER 1 WEEK 2 PLOT, POV AND CONFLICTS
KynaParas
 
PDF
Horarios de distribución de agua en julio
pegazohn1978
 
PPTX
How to Convert an Opportunity into a Quotation in Odoo 18 CRM
Celine George
 
PPTX
GRADE-3-PPT-EVE-2025-ENG-Q1-LESSON-1.pptx
EveOdrapngimapNarido
 
PPT
Talk on Critical Theory, Part One, Philosophy of Social Sciences
Soraj Hongladarom
 
PPTX
PPT-Q1-WEEK-3-SCIENCE-ERevised Matatag Grade 3.pptx
reijhongidayawan02
 
PPTX
HUMAN RESOURCE MANAGEMENT: RECRUITMENT, SELECTION, PLACEMENT, DEPLOYMENT, TRA...
PRADEEP ABOTHU
 
PDF
ARAL-Orientation_Morning-Session_Day-11.pdf
JoelVilloso1
 
PPTX
Post Dated Cheque(PDC) Management in Odoo 18
Celine George
 
PDF
Aprendendo Arquitetura Framework Salesforce - Dia 03
Mauricio Alexandre Silva
 
PDF
Knee Extensor Mechanism Injuries - Orthopedic Radiologic Imaging
Sean M. Fox
 
How to Create Odoo JS Dialog_Popup in Odoo 18
Celine George
 
Reconstruct, Restore, Reimagine: New Perspectives on Stoke Newington’s Histor...
History of Stoke Newington
 
I AM MALALA The Girl Who Stood Up for Education and was Shot by the Taliban...
Beena E S
 
DIGESTION OF CARBOHYDRATES,PROTEINS,LIPIDS
raviralanaresh2
 
Biological Bilingual Glossary Hindi and English Medium
World of Wisdom
 
Dimensions of Societal Planning in Commonism
StefanMz
 
CONCURSO DE POESIA “POETUFAS – PASSOS SUAVES PELO VERSO.pdf
Colégio Santa Teresinha
 
CATEGORIES OF NURSING PERSONNEL: HOSPITAL & COLLEGE
PRADEEP ABOTHU
 
Growth and development and milestones, factors
BHUVANESHWARI BADIGER
 
QUARTER 1 WEEK 2 PLOT, POV AND CONFLICTS
KynaParas
 
Horarios de distribución de agua en julio
pegazohn1978
 
How to Convert an Opportunity into a Quotation in Odoo 18 CRM
Celine George
 
GRADE-3-PPT-EVE-2025-ENG-Q1-LESSON-1.pptx
EveOdrapngimapNarido
 
Talk on Critical Theory, Part One, Philosophy of Social Sciences
Soraj Hongladarom
 
PPT-Q1-WEEK-3-SCIENCE-ERevised Matatag Grade 3.pptx
reijhongidayawan02
 
HUMAN RESOURCE MANAGEMENT: RECRUITMENT, SELECTION, PLACEMENT, DEPLOYMENT, TRA...
PRADEEP ABOTHU
 
ARAL-Orientation_Morning-Session_Day-11.pdf
JoelVilloso1
 
Post Dated Cheque(PDC) Management in Odoo 18
Celine George
 
Aprendendo Arquitetura Framework Salesforce - Dia 03
Mauricio Alexandre Silva
 
Knee Extensor Mechanism Injuries - Orthopedic Radiologic Imaging
Sean M. Fox
 
Ad

Write a function to merge two doubly linked lists. The input lists ha.pdf

  • 1. Write a function to merge two doubly linked lists. The input lists have their elements in sorted order, from lowest to highest. The output list should also be sorted from lowest to highest. Your algorithm should run in linear time on the length of the output list. Provide an algorithm for your function Implement and show some samples of your running function Solution The algorithm for LinkedList MergeSort is as follows. The trick in this algorithm is to use a local list to store the value which is pointing to the actual list to be returned as a result of the function Step1: START Step2: GET inputs of list1 and list2 Step3: INITIALIZE mergelist STEP4: SET mylist = mergelist Step5: WHILE list1 OR list2 is EMPTY DO IF (list1 AND list2) are NOT EMPTY IF list1.value > list2.value mylist.next = list2 ELSE mylist.next = list1 ELSE IF list1 is EMPTY mylist.next = list2 ELSE mylist.next = list1 Step6: RETURN mergelist Step7: STOP Sample program for the same implemented in C++ //==================================================================== ======== // Name : DoublyLinkedList.cpp // Author : Kaju // Version : 0.1 // Copyright : This is just an example code // Description : MergeSort in C++, Ansi-style
  • 2. //==================================================================== ======== /* * C++ Program to Implement Doubly Linked List */ #include #include #include /* * Node Declaration */ using namespace std; // struct declaration for node which will hold the integer data with links to previous data and next data struct node { int data; struct node *next; struct node *prev; }; /* Class Declaration */ class DoublyLinkedList { private: struct node *start; // collection of all the nodes public: void create(int value); int peek(); int delete_head(); void display(); int count(); void mergeSort(DoublyLinkedList list1, DoublyLinkedList list2); DoublyLinkedList() {
  • 3. start = NULL; } }; /* * Add data into the list */ void DoublyLinkedList::create(int value) { struct node *s, *temp; temp = new(struct node); temp->data = value; temp->next = NULL; if (start == NULL) { temp->prev = NULL; start = temp; } else { s = start; while (s->next != NULL) s = s->next; s->next = temp; temp->prev = s; } } /* * Deletion of the first element from the list * store the first element in a temp node and then remove it from start. */ int DoublyLinkedList::delete_head() { struct node *tmp, *q; int value; tmp = start; if(start->next!=NULL)
  • 4. { start = start->next; start->prev = NULL; } else start = NULL; value = tmp->data; free(tmp); return value; } /* * return the first element of Doubly Link List */ int DoublyLinkedList::peek() { struct node *q; if (start == NULL) { cout<<"List is empty"<data; } } /* * Display elements of Doubly Link List */ void DoublyLinkedList::display() { struct node *q; if (start == NULL) { cout<<"List is empty"<data; q = q->next; if(q != NULL) { cout<<", "; } }
  • 5. cout<<"]"<next; cnt++; } return cnt; } /* * MergeSort - takes two input lists and then based on the integer data value sorts them in ascending order. * Adds each data removed from the input lists into the new list. */ void DoublyLinkedList::mergeSort(DoublyLinkedList list1, DoublyLinkedList list2) { while(list1.count() > 0 || list2.count() > 0) // Checks whether any of the list is empty { if(list1.count() > 0 && list2.count() > 0) // checks if both the lists have data { if(list1.peek() > list2.peek()) // compares the first element of both the lists create(list2.delete_head()); // if the second list has greater value then it is removed from the second list and added to the new list else create(list1.delete_head());// if the first list has greater value then it is removed from the first list and added to the new list } else if(list1.count() == 0) // incase where list one is empty and only list two has value { create(list2.delete_head()); // if the second list has value then it is removed from the second list and added to the new list } else { create(list1.delete_head()); // if the first list has value then it is removed from the first list and added to the new list } } } int main()
  • 6. { DoublyLinkedList firstList; firstList.create(4); firstList.create(10); firstList.create(45); firstList.create(53); firstList.create(250); firstList.create(1020); cout<<"List 1: "; firstList.display(); DoublyLinkedList secondList; secondList.create(1); secondList.create(36); secondList.create(68); secondList.create(73); secondList.create(1019); cout<<"List 2: "; secondList.display(); DoublyLinkedList mergedList; mergedList.mergeSort(firstList, secondList); cout<<"Merged List: "; mergedList.display(); return 0; } OUTPUT: List 1: [4, 10, 45, 53, 250, 1020] List 2: [1, 36, 78, 673, 1019] Merged List: [1, 4, 10, 36, 45, 53, 78, 250, 673, 1019, 1020]