if i try to add at 0th position it doesnot work or if i try to add first element using insertInmiddle(3,5,head)
as head is NULL so it should be added using insertInHead
but my condition if(position==0 || head == NULL) is not working
plzz check
insertInMiddle confusion
Hello @yatin,
I would suggest you to use print statements to check if a part of code is executing or not.
I check your code that condition is working perfectly.
The main issue is with the head.
You passing head in all functions and then changes the value/node it is pointing to.
This is causing the wrong output.
Solution: Rather use a temporary variable of type node.
I have modified your code. You can check it here.
Hope, this would help.
Give a like if you are satisfied.
sir what is the use of creating temporary node
as i am passing a copy of head only
and in temp also i will be copying head into it
where is the difference?
sir plzz clear my doubt??
Hello @yatin,
I am really sorry for replying this late.
The problem is in the parameter of insertInMiddle() function:
If you notice in your code,
You are not passing head by reference in the insertIMiddle(), thus a copy of head is made.
But, when the following code executes:
if(position==0 || head==NULL ) //if position ==0 then user wants to add at head || if head==NULL i
{ //is the first node
insertInHead(head,data);
}
You are passing head by reference.
Thus, the changes that would be made would reflect on the copy of head, not on the actual head.
Solution:
Pass head by reference in insertInMiddle() function.
Hope, this would help.
Give a like, if you are satisfied.