Question

In C++ Assuming: struct node { int data; node * next; }; and copyList(node * head);...

In C++

Assuming:
struct node
{
    int data;
    node * next;
};

and 
copyList(node * head);

Write a recursive function (copyList(node * head)) that will create a copy of the singly linked list.

0 0
Add a comment Improve this question Transcribed image text
Answer #1
#include <iostream>

using namespace std;

struct node
{
    int data;
    node * next;
};

node *copyList(node * head) {
    if(head == NULL) {
        return NULL;
    } else {
        node *copy = new node;
        copy->data = head->data;
        copy->next = copyList(head->next);
        return copy;
    }
}

int main() {
    node *original_list = new node;
    original_list->data = 5;
    original_list->next = new node;
    original_list->next->data = 2;
    original_list->next->next = new node;
    original_list->next->next->data = 9;
    original_list->next->next->next = NULL;

    node *copy_list = copyList(original_list);
    node *temp = copy_list;
    while (temp != NULL) {
        cout << temp->data << " ";
        temp = temp->next;
    }
    cout << endl;

    return 0;
}

5 2 9

Add a comment
Know the answer?
Add Answer to:
In C++ Assuming: struct node { int data; node * next; }; and copyList(node * head);...
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