It was all going well until the pointers came in!
Has this statement ever crossed your mind?
But you should know that the pointer is an important concept to know. A pointer is used to implement a lot many things in C++. Linked List is one of them. Linked List uses pointers for its operation.
Today we will be looking at how to insert a node at the beginning of a Linked List.
In the picture below you can see, we want to insert node d at the beginning of the list given. To insert it at the beginning, we followed three steps,
1) create a new node i.e. temp
2) the next of temp should be head now
3) At last, head = temp
Now, the new node temp is inserted at the beginning.
Lets look at the code!
Below is the function for inserting at the beginning. It will take an integer argument which will contain the value to be inserted in the node that is to be inserted at the beginning.
In the function, at the very first, we will create a new node by the code given below. I will create a new node named temp.
Now we will assign the data n to the new node temp.
After assigning the data to the node now the next to temp should have the address of the current head of the linked list before which we want to insert the new node temp. We will do it by assigning temp->next = head,
Now that our node temp is holding the address of its next node, we will assign temp to head. Since now, the temp is the first node of our linked list.
So here we are done with inserting the node temp at the beginning of the linked list.
So the entire function looks like,
In the above code, display(head) is another function which is used to display the entire linked list. So lets take a brief look at display function.
Below give is the entire display function. This function takes in pointer as an argument. This pointer will bring the address of the node to be printed.Recursion is used hear where we again pass h->next to the function display until the value of the pointer is equal to NULL.
Now we will look at the entire program to insert a node at the beginning.
In the above program we have the following,
1) structure node
2) class linked_list
3) a constructor linked_list() inside the class linked_list to initialise the value of head and tail to NULL at the very beginning
4) a function front() to insert at the beginning
5) a function display() to display the linked list
No comments:
Post a Comment