Professional Documents
Culture Documents
Experiment 3
Experiment 3
• 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;
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: