Explain how to create new node holding data “34” and making it part of the list.
Question
Explain how to create a new node holding data “34” and make it part of the list. Clarify with the help of a pictorial representation of the process.
Summary
A linked list is a linear data structure in which each element/node of the list points to the next element/node in the list. A single linked list is nothing more than a set of nodes (nodes hold the data and the pointer to the next node).
It appears to be as follows
It is necessary to examine the header when inserting it into a linked list. The header is a global pointer to the beginning of the linked list.
We store the data in the header if it is empty. Last, add another global variable to it.
Then, for any subsequent data, we use ‘new’ to dynamically create a node and save the value in it. The next of last is then set to the new node, while the next of new node is set to NULL.
Finally, we update the last node to the new one.
Code
#include<iostream> #include<string> using namespace std; //node structure of the linkedlist struct node { int value; struct node *next; }; struct node *header=NULL, *last; //function declarations void create(int no); void display(); int main() { create(12); create(66); create(99); cout<<"Initially the list is: "; //call display function display(); //function call to insert 34 create(34); cout<<"\nAfter inertion of 34 the list is: "; display(); return 0; } //function to create list void create(int no) { //creation of new node struct node *new_node= new node; new_node->value=no; new_node->next=NULL; //insertion of the node in list if(header==NULL) { //if the list is empty header=new_node; last=new_node; } else { //add at the end last->next=new_node; last=new_node; } } //function to display list content void display() { struct node *temp; temp=header; while(temp!=NULL) { cout<<"--"<<temp->value; temp=temp->next; } }
Output
Also, read check the python code below that doesn’t work properly, adjust it, and explain?