Insert a new node at the beginning of the linked list

PHOTO EMBED

Sun Jul 24 2022 15:28:39 GMT+0000 (Coordinated Universal Time)

Saved by @sahmal #c++ #algorithm #dsa #sorting #insertionsort #insertion

#include<iostream>
using namespace std;
struct Node {
public:
	int data;
	Node* next;
	Node(int data=0)
	{
		this->data = data;
		this->next = NULL;
	}
};
void push(Node** head_ref, int data) {
	//creating the new node and by using constructor we 
	//are storing the value of the data
	//firstly the next pointer of this new node points to NULL
	//as declared in the constructor
	//then we are pointing the pointer of this node to the new node
	//and lastly we are equating the new insert node to the previous 
	//node to connect it to the list
	Node* new_node = new Node(data);
	new_node->next =(* head_ref);
	*(head_ref) = new_node;

}
void print(Node*& head) {

	Node* temp =  head;
	while (temp != NULL)
	{
		cout << "the value of the data is " << temp->data << endl;
		temp = temp->next;
	}

}

int main() {
	Node* node;
	node = NULL;
	push(&node, 5);
	push(&node, 6);
	push(&node, 7);
	print(node);
	return 0;


}
content_copyCOPY

insert a new node at the beginning of the linked list