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

STAGE 2 The Methods 65 points Implement all the methods t.pdf
STAGE 2 The Methods 65 points Implement all the methods t.pdfSTAGE 2 The Methods 65 points Implement all the methods t.pdf
STAGE 2 The Methods 65 points Implement all the methods t.pdf
babitasingh698417
 
The LinkedList1 class implements a Linked list. class.pdf
The LinkedList1 class implements a Linked list. class.pdfThe LinkedList1 class implements a Linked list. class.pdf
The LinkedList1 class implements a Linked list. class.pdf
malavshah9013
 
C++ problemPart 1 Recursive Print (40 pts)Please write the recu.pdf
C++ problemPart 1 Recursive Print (40 pts)Please write the recu.pdfC++ problemPart 1 Recursive Print (40 pts)Please write the recu.pdf
C++ problemPart 1 Recursive Print (40 pts)Please write the recu.pdf
callawaycorb73779
 
Csphtp1 23
Csphtp1 23Csphtp1 23
Csphtp1 23
HUST
 
Csphtp1 23
Csphtp1 23Csphtp1 23
Csphtp1 23
HUST
 
Class DiagramIn the Assignment #10, you are given three files Ass.pdf
Class DiagramIn the Assignment #10, you are given three files Ass.pdfClass DiagramIn the Assignment #10, you are given three files Ass.pdf
Class DiagramIn the Assignment #10, you are given three files Ass.pdf
xlynettalampleyxc
 
Lec-4_Linked-List (1).pdf
Lec-4_Linked-List (1).pdfLec-4_Linked-List (1).pdf
Lec-4_Linked-List (1).pdf
KylaMaeGarcia1
 
File LinkedList.java Defines a doubly-l.pdf
File LinkedList.java Defines a doubly-l.pdfFile LinkedList.java Defines a doubly-l.pdf
File LinkedList.java Defines a doubly-l.pdf
Conint29
 
How do you stop infinite loop Because I believe that it is making a.pdf
How do you stop infinite loop Because I believe that it is making a.pdfHow do you stop infinite loop Because I believe that it is making a.pdf
How do you stop infinite loop Because I believe that it is making a.pdf
feelinggift
 
Please help solve this in C++ So the program is working fin.pdf
Please help solve this in C++ So the program is working fin.pdfPlease help solve this in C++ So the program is working fin.pdf
Please help solve this in C++ So the program is working fin.pdf
ankit11134
 
Problem- Describe an algorithm for concatenating two singly linked lis.pdf
Problem- Describe an algorithm for concatenating two singly linked lis.pdfProblem- Describe an algorithm for concatenating two singly linked lis.pdf
Problem- Describe an algorithm for concatenating two singly linked lis.pdf
JamesPXNNewmanp
 
C++ Doubly-Linked ListsThe goal of the exercise is to implement a.pdf
C++ Doubly-Linked ListsThe goal of the exercise is to implement a.pdfC++ Doubly-Linked ListsThe goal of the exercise is to implement a.pdf
C++ Doubly-Linked ListsThe goal of the exercise is to implement a.pdf
poblettesedanoree498
 
Linked list
Linked list Linked list
Linked list
Arbind Mandal
 
Data Structures in C++I am really new to C++, so links are really .pdf
Data Structures in C++I am really new to C++, so links are really .pdfData Structures in C++I am really new to C++, so links are really .pdf
Data Structures in C++I am really new to C++, so links are really .pdf
rohit219406
 
Array linked list.ppt
Array  linked list.pptArray  linked list.ppt
Array linked list.ppt
Waf1231
 
Adt of lists
Adt of listsAdt of lists
Adt of lists
Nivegeetha
 
import java.util.LinkedList; import java.util.Random; import jav.pdf
import java.util.LinkedList; import java.util.Random; import jav.pdfimport java.util.LinkedList; import java.util.Random; import jav.pdf
import java.util.LinkedList; import java.util.Random; import jav.pdf
aquastore223
 
Describe an algorithm for concatenating two singly linked lists L and.pdf
Describe an algorithm for concatenating two singly linked lists L and.pdfDescribe an algorithm for concatenating two singly linked lists L and.pdf
Describe an algorithm for concatenating two singly linked lists L and.pdf
deepak596396
 
linked List.docx vhjgvjhvgjhjhbbjkhkjhkjh
linked List.docx vhjgvjhvgjhjhbbjkhkjhkjhlinked List.docx vhjgvjhvgjhjhbbjkhkjhkjh
linked List.docx vhjgvjhvgjhjhbbjkhkjhkjh
vasavim9
 
Select three methods in the ObjectList class to work through algori.pdf
Select three methods in the ObjectList class to work through algori.pdfSelect three methods in the ObjectList class to work through algori.pdf
Select three methods in the ObjectList class to work through algori.pdf
aroraopticals15
 

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

STAGE 2 The Methods 65 points Implement all the methods t.pdf
STAGE 2 The Methods 65 points Implement all the methods t.pdfSTAGE 2 The Methods 65 points Implement all the methods t.pdf
STAGE 2 The Methods 65 points Implement all the methods t.pdf
 
The LinkedList1 class implements a Linked list. class.pdf
The LinkedList1 class implements a Linked list. class.pdfThe LinkedList1 class implements a Linked list. class.pdf
The LinkedList1 class implements a Linked list. class.pdf
 
C++ problemPart 1 Recursive Print (40 pts)Please write the recu.pdf
C++ problemPart 1 Recursive Print (40 pts)Please write the recu.pdfC++ problemPart 1 Recursive Print (40 pts)Please write the recu.pdf
C++ problemPart 1 Recursive Print (40 pts)Please write the recu.pdf
 
Csphtp1 23
Csphtp1 23Csphtp1 23
Csphtp1 23
 
Csphtp1 23
Csphtp1 23Csphtp1 23
Csphtp1 23
 
Class DiagramIn the Assignment #10, you are given three files Ass.pdf
Class DiagramIn the Assignment #10, you are given three files Ass.pdfClass DiagramIn the Assignment #10, you are given three files Ass.pdf
Class DiagramIn the Assignment #10, you are given three files Ass.pdf
 
Lec-4_Linked-List (1).pdf
Lec-4_Linked-List (1).pdfLec-4_Linked-List (1).pdf
Lec-4_Linked-List (1).pdf
 
File LinkedList.java Defines a doubly-l.pdf
File LinkedList.java Defines a doubly-l.pdfFile LinkedList.java Defines a doubly-l.pdf
File LinkedList.java Defines a doubly-l.pdf
 
How do you stop infinite loop Because I believe that it is making a.pdf
How do you stop infinite loop Because I believe that it is making a.pdfHow do you stop infinite loop Because I believe that it is making a.pdf
How do you stop infinite loop Because I believe that it is making a.pdf
 
Please help solve this in C++ So the program is working fin.pdf
Please help solve this in C++ So the program is working fin.pdfPlease help solve this in C++ So the program is working fin.pdf
Please help solve this in C++ So the program is working fin.pdf
 
Problem- Describe an algorithm for concatenating two singly linked lis.pdf
Problem- Describe an algorithm for concatenating two singly linked lis.pdfProblem- Describe an algorithm for concatenating two singly linked lis.pdf
Problem- Describe an algorithm for concatenating two singly linked lis.pdf
 
C++ Doubly-Linked ListsThe goal of the exercise is to implement a.pdf
C++ Doubly-Linked ListsThe goal of the exercise is to implement a.pdfC++ Doubly-Linked ListsThe goal of the exercise is to implement a.pdf
C++ Doubly-Linked ListsThe goal of the exercise is to implement a.pdf
 
Linked list
Linked list Linked list
Linked list
 
Data Structures in C++I am really new to C++, so links are really .pdf
Data Structures in C++I am really new to C++, so links are really .pdfData Structures in C++I am really new to C++, so links are really .pdf
Data Structures in C++I am really new to C++, so links are really .pdf
 
Array linked list.ppt
Array  linked list.pptArray  linked list.ppt
Array linked list.ppt
 
Adt of lists
Adt of listsAdt of lists
Adt of lists
 
import java.util.LinkedList; import java.util.Random; import jav.pdf
import java.util.LinkedList; import java.util.Random; import jav.pdfimport java.util.LinkedList; import java.util.Random; import jav.pdf
import java.util.LinkedList; import java.util.Random; import jav.pdf
 
Describe an algorithm for concatenating two singly linked lists L and.pdf
Describe an algorithm for concatenating two singly linked lists L and.pdfDescribe an algorithm for concatenating two singly linked lists L and.pdf
Describe an algorithm for concatenating two singly linked lists L and.pdf
 
linked List.docx vhjgvjhvgjhjhbbjkhkjhkjh
linked List.docx vhjgvjhvgjhjhbbjkhkjhkjhlinked List.docx vhjgvjhvgjhjhbbjkhkjhkjh
linked List.docx vhjgvjhvgjhjhbbjkhkjhkjh
 
Select three methods in the ObjectList class to work through algori.pdf
Select three methods in the ObjectList class to work through algori.pdfSelect three methods in the ObjectList class to work through algori.pdf
Select three methods in the ObjectList class to work through algori.pdf
 

More from info706022

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

More from info706022 (20)

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

Recently uploaded

Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
beazzy04
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
siemaillard
 
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
Nguyen Thanh Tu Collection
 
Fish and Chips - have they had their chips
Fish and Chips - have they had their chipsFish and Chips - have they had their chips
Fish and Chips - have they had their chips
GeoBlogs
 
PART A. Introduction to Costumer Service
PART A. Introduction to Costumer ServicePART A. Introduction to Costumer Service
PART A. Introduction to Costumer Service
PedroFerreira53928
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
EugeneSaldivar
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
Special education needs
 
ESC Beyond Borders _From EU to You_ InfoPack general.pdf
ESC Beyond Borders _From EU to You_ InfoPack general.pdfESC Beyond Borders _From EU to You_ InfoPack general.pdf
ESC Beyond Borders _From EU to You_ InfoPack general.pdf
Fundacja Rozwoju Społeczeństwa Przedsiębiorczego
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
BhavyaRajput3
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
MIRIAMSALINAS13
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
Balvir Singh
 
Ethnobotany and Ethnopharmacology ......
Ethnobotany and Ethnopharmacology ......Ethnobotany and Ethnopharmacology ......
Ethnobotany and Ethnopharmacology ......
Ashokrao Mane college of Pharmacy Peth-Vadgaon
 
Cambridge International AS A Level Biology Coursebook - EBook (MaryFosbery J...
Cambridge International AS  A Level Biology Coursebook - EBook (MaryFosbery J...Cambridge International AS  A Level Biology Coursebook - EBook (MaryFosbery J...
Cambridge International AS A Level Biology Coursebook - EBook (MaryFosbery J...
AzmatAli747758
 
1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx
JosvitaDsouza2
 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
Atul Kumar Singh
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
EverAndrsGuerraGuerr
 
Introduction to Quality Improvement Essentials
Introduction to Quality Improvement EssentialsIntroduction to Quality Improvement Essentials
Introduction to Quality Improvement Essentials
Excellence Foundation for South Sudan
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
Sandy Millin
 
How to Break the cycle of negative Thoughts
How to Break the cycle of negative ThoughtsHow to Break the cycle of negative Thoughts
How to Break the cycle of negative Thoughts
Col Mukteshwar Prasad
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
kaushalkr1407
 

Recently uploaded (20)

Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
 
Fish and Chips - have they had their chips
Fish and Chips - have they had their chipsFish and Chips - have they had their chips
Fish and Chips - have they had their chips
 
PART A. Introduction to Costumer Service
PART A. Introduction to Costumer ServicePART A. Introduction to Costumer Service
PART A. Introduction to Costumer Service
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
 
ESC Beyond Borders _From EU to You_ InfoPack general.pdf
ESC Beyond Borders _From EU to You_ InfoPack general.pdfESC Beyond Borders _From EU to You_ InfoPack general.pdf
ESC Beyond Borders _From EU to You_ InfoPack general.pdf
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
 
Ethnobotany and Ethnopharmacology ......
Ethnobotany and Ethnopharmacology ......Ethnobotany and Ethnopharmacology ......
Ethnobotany and Ethnopharmacology ......
 
Cambridge International AS A Level Biology Coursebook - EBook (MaryFosbery J...
Cambridge International AS  A Level Biology Coursebook - EBook (MaryFosbery J...Cambridge International AS  A Level Biology Coursebook - EBook (MaryFosbery J...
Cambridge International AS A Level Biology Coursebook - EBook (MaryFosbery J...
 
1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx
 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
 
Introduction to Quality Improvement Essentials
Introduction to Quality Improvement EssentialsIntroduction to Quality Improvement Essentials
Introduction to Quality Improvement Essentials
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
 
How to Break the cycle of negative Thoughts
How to Break the cycle of negative ThoughtsHow to Break the cycle of negative Thoughts
How to Break the cycle of negative Thoughts
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
 

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]