Download as pdf or txt
Download as pdf or txt
You are on page 1of 5

Experiment – 3

Student Name: Aniket Sugara UID: 20BCS7284


Branch: BE-CSE Section/Group: 619-A
Semester: 5 Date of Performance: 12/09/22
Subject Name: Competitive Coding – I Subject Code: 20CSP-312

Q1. Compare two linked lists


Link:https://www.hackerrank.com/challenges/compare-two-linked-
lists/problem?isFullScreen=true

• Code:
bool compare_lists(SinglyLinkedListNode* head1, SinglyLinkedListNode* head2) {
auto p1 = head1;
auto p2 = head2;
while (p1 != nullptr && p2 != nullptr && p1->data == p2->data) {
p1 = p1->next;
p2 = p2->next;
}
if (p1 == nullptr && p2 == nullptr) return 1;
else return 0;
}

• Output:
Q2. Inserting a Node Into a Sorted Doubly Linked List
Link: https://www.hackerrank.com/challenges/insert-a-node-into-a-sorted-doubly-linked-
list/problem?isFullScreen=true

• Code:
DoublyLinkedListNode* sortedInsert(DoublyLinkedListNode* llist, int data) {
DoublyLinkedListNode* ptr=llist;
DoublyLinkedListNode* tempo;
DoublyLinkedListNode *temp = new DoublyLinkedListNode(data);

if(llist==NULL)
return llist;

if(llist->data>=temp->data) {
llist->prev=temp;
temp->next=llist;
return temp;
}

while(llist->data<data) {
if(llist->next==NULL) {
llist->next=temp;
temp->prev=llist;
return ptr;
}
llist=llist->next;
}

tempo=llist->prev;
tempo->next=temp;
temp->prev=tempo;
temp->next=llist;
return ptr;
}
• Output:
Q3. Reverse a Doubley Linked List
Link:https://www.hackerrank.com/challenges/reverse-a-doubly-linked-
list/problem?isFullScreen=true

• Code:
DoublyLinkedListNode* reverse(DoublyLinkedListNode* llist) {
if(llist == NULL)
cout << "list is null" << endl;

else if(llist->next == NULL)


return llist;

DoublyLinkedListNode* curr = llist;


DoublyLinkedListNode* nextNode = llist;

while(curr != NULL){
nextNode = curr->next;
curr->next = curr->prev;
curr->prev = nextNode;
llist = curr;
curr = nextNode;
}
return llist;
}

• Output:
Q4. Find Merge Point of Two Lists
Link:https://www.hackerrank.com/challenges/find-the-merge-point-of-two-joined-linked-
lists/problem?isFullScreen=true

• Code:
int findMergeNode(SinglyLinkedListNode* head1, SinglyLinkedListNode* head2) {
SinglyLinkedListNode* node1 = head1;
SinglyLinkedListNode* node2 = head2;
set<SinglyLinkedListNode*> s;
while(node1){
s.insert(node1);
node1 = node1->next;
}
while(node2){
if(s.find(node2)!=s.end())
return node2->data;
node2 = node2->next;
}
return 0;
}

• Output:

You might also like