Question

Hello, how do I create a new singly linked list by concatenating two existing singly linked...

Hello, how do I create a new singly linked list by concatenating two existing singly linked list in c++? Thank you!
0 0
Add a comment Improve this question Transcribed image text
Answer #1

You have to check these, 3 condition first-:

1.) If list 1 is empty or not.

o> If list 1 is empty then concatenated list will be list 2 only.

2.) If list 2 is empty or not.

o>If list 2 is empty than concatenated list will be list 1 only.

3. If both lists are empty or not.

o>concatenated list will be empty list.

Suppose that our two lists are non-empty linked list, list 1 has start_1 pointer as head pointer and list 2 has start_2 as head pointer.

TO CONCATENATE THE 2 NON-EMPTY LISTS WE NEED TO FOLLOW BELOW STEPS-:

1. Make a pointer 'p' which point to start_1.

2. Take that pointer to last element(node) of list 1 which contains address as NULL.

3. Store the address of first element of list 2 in address field of last node of list 1.

Now you are ready with your concatenated list;)

Algorithm to concatenate 2 linked list-:

node * concatenate (node *start_1, node *start_2)

{

node*p;

                if (start_1==NULL)                            //if the first linked list is empty

                return(start_2);

                if (start_2==NULL)                            //if second linked list is empty

                return (start_1);

                p=start_1;     //place p on the first node of the first linked list

             while (p->next!=NULL)                 //move p to the last node

                                p=p->next;

                p->next=start_2;       //address of the first node of the second linked list stored in the last node of the first linked list return(start_1);

}

C++ CODE

OUTPUT

Add a comment
Know the answer?
Add Answer to:
Hello, how do I create a new singly linked list by concatenating two existing singly linked...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT