0% found this document useful (0 votes)
7 views

Code CPP

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

Code CPP

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

// C++ program to concat two singly

// linked lists

#include <bits/stdc++.h>

using namespace std;

struct Node {

int data;

Node* next;

Node(int x) {

data = x;

next = nullptr;

};

// Function to concatenate two linked lists

Node* concat(Node* head1, Node* head2) {

if (head1 == nullptr)

return head2;

// Find the last node of the first list

Node* curr = head1;

while (curr->next != nullptr) {

curr = curr->next;

// Link the last node of the first list

// to the head of the second list

curr->next = head2;
// Return the head of the concatenated list

return head1;

void printList(Node* head) {

Node* curr = head;

while (curr != nullptr) {

cout << curr->data << " ";

curr = curr->next;

cout << endl;

int main() {

// Create first linked list: 1 -> 2 -> 3

Node* head1 = new Node(1);

head1->next = new Node(2);

head1->next->next = new Node(3);

// Create second linked list: 4 -> 5

Node* head2 = new Node(4);

head2->next = new Node(5);

Node* concatHead = concat(head1, head2);

printList(concatHead);

return 0;

You might also like