Question

Write a C++ function to add a node to the beginning of a linked list. Your...

Write a C++ function to add a node to the beginning of a linked list.

Your function takes two arguments - the head of the linked list and the value num to be added.
Note that the list may be empty!

Your function should modify the head of the linked list to point to the new node, and set the new node to point to the rest of the list (if not empty).

Example:

Initial Array: 4->2->3, key = 5

Array After Function Call: 5->4->2->3

void AddNode(node** head, int num);

The linked list structure:

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

The objective is to understand how to make use of a pointer-to-a-pointer, and why it is important.

For example:

Test Result
// head = 4
// AddNode(head, 2)
// AddNode(head, 3)
// AddNode(head, 5)
5->3->2->4
0 0
Add a comment Improve this question Transcribed image text
Answer #1
#include <iostream>
using namespace std;

struct Node
{
    int val;
    Node *next; //it should Node instead of node
};


/*Note if our list is empty then head must point to nullptr*/
void Add(Node **head, int key){
    Node *temp = new Node;  //Allocate memory for new node to be added
    temp->val = key;        //assign key value
    temp->next = *head;      //setting next of newly created node to head node to complete link
    *head = temp;            //make newly created node head node
}

// main function to work correctness of Add function
int main(){
    Node *head = new Node;
    head->val = 4;
    head->next = nullptr;

    Add(&head, 2);  //Now we have to pass address of head node
    Add(&head, 3);
    Add(&head, 5);

    Node *temp = head;
    while(temp->next != nullptr){
        cout<<temp->val<<"->";
        temp = temp->next;
    }
    cout<<temp->val<<endl;


    return 0;
}

Add a comment
Know the answer?
Add Answer to:
Write a C++ function to add a node to the beginning of a linked list. Your...
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