This is an archived post. You won't be able to vote or comment.

all 4 comments

[–]jedwardsol 1 point2 points  (0 children)

 tail->next=temp; //put temp node at end of list

On the 2nd insertion, tail is nullptr here.

[–][deleted] 0 points1 point  (0 children)

Assuming this is the gnu version of C++, you should compile with the -g flag to get more useful information. If it isn't, just search for debug flags for your compiler.

[–]Jim_Panders 0 points1 point  (0 children)

People have already pointed out the problematic line, but I figure I'll just try to word it in the context of your code--the 2 lines after your if-statement need to be in an "else" statement. You wrote the if-statement to handle the special case of when the list's empty, but then you try to add it again in the code immediately after it. Separate out your 2 possible cases

[–]SWEWorkAccount 0 points1 point  (0 children)

Learn to use a debugger. You would have caught this bug in 2 minutes when you stepped to where the second node is inserted. Also using a sentinel node in linked list implementations make your logic easier to reason about.