In this post, we will discuss a method to add one to a number which is represented using nodes of the linked list.
This problem becomes very simple if the given linked list is considered to be doubly linked list as it is easier to add one to the number at the end of the linked list and traverse the list from backward direction till carry becomes zero. but if the given linked list is a singly linked list then we have to first reverse the given linked list and then add one to the first node. So considering our linked list is a simple linked list we follow the below steps.
Algorithm:
Algorithm:
- Reverse the linked list.
- Add one to the data field of the first node.
- While carry is not zero keep adding carry to the next node's data field
- if you reach the end of the linked list and the carry is not zero then we add a new node to the end of the linked list.
- Reverse the final linked list and return the head node of the linked list.
Comments
Post a Comment