SlideShare a Scribd company logo
1 of 6
Download to read offline
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
 
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
 
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
 
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
 
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
 
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

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
 
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
 
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
 
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
 

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

Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
negromaestrong
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
ciinovamais
 
Gardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch LetterGardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch Letter
MateoGardella
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
PECB
 

Recently uploaded (20)

Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
Gardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch LetterGardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch Letter
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writing
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).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]