0% found this document useful (0 votes)
16 views4 pages

Dsal Assignment 2

Uploaded by

70116381
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views4 pages

Dsal Assignment 2

Uploaded by

70116381
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 4

DSA LAB

ASSIGNMENT NO 2

SUBMITTED BY: HIRA ATIF(421)


SUBMITTED TO: IQRA KHALIL
Two linked lists and merging them

#include <iostream>
using namespace std;

class Node
{
public:
int data;
Node *next;

Node(int n)
{
data = n;
next = nullptr;
}
};

class LinkedList
{
private:
Node *head;

public:
LinkedList()
{
head = nullptr;
}

void append(int n)
{
Node *newNode = new Node(n);

if (head == nullptr)
{
head = newNode;
return;
}

Node *temp = head;


while (temp->next != nullptr)
{
temp = temp->next;
}
temp->next = newNode;
}

void display()
{
Node *temp = head;
while (temp != nullptr)
{
cout << temp->data <<" ";
temp = temp->next;
}
cout << "null" << endl;
}

static LinkedList merge(const LinkedList &l1, const LinkedList &l2){


LinkedList mergedList;
Node *temp1 = l1.head;
Node *temp2 = l2.head;

while (temp1 != nullptr && temp2 != nullptr)


{
if (temp1->data <= temp2->data)
{
mergedList.append(temp1->data);
temp1 = temp1->next;
}
else
{
mergedList.append(temp2->data);
temp2 = temp2->next;
}
}

while (temp1 != nullptr)


{
mergedList.append(temp1->data);
temp1 = temp1->next;
}

while (temp2 != nullptr)


{
mergedList.append(temp2->data);
temp2 = temp2->next;
}
return mergedList;
}

};

int main()
{
LinkedList l1,l2;

l1.append(1);
l1.append(3);
l1.append(4);

l2.append(1);
l2.append(2);
l2.append(4);

cout << "First list: "<<endl;


l1.display();
cout<<"Second list: "<<endl;
l2.display();

LinkedList mergList = LinkedList :: merge(l1,l2);


cout<<"Merged linkedlist: "<<endl;
mergList.display();

return 0;
}

Output

You might also like