# Insert a Node at the Tail of a Linked List

# Insert a Node at the Tail of a Linked List

devasood + 8 comments seriously, show main function as uneditable.. its tough to debug with "wrong answer" and "right answer"

ravi1008Asked to answer + 6 comments Could you just share your code so that I can examine it and help you out.

Even I suffer a lot while coding in hackerrank due to "uneditable" part like main() function. But you can always print the intermediate results to cross check the code flow and approach.

ankeet_s + 9 comments Node Insert(Node head,int data) { Node tmp = new Node(); tmp.data = data; tmp.next = null;

`if(head == null) { head = tmp; return head; } Node current = head; while(current.next != null) { current = current.next; } current.next = tmp; return head;`

}

navkhan + 2 comments how does this work? there is no link between the 2ndlast item (formerly the last) and the new one just added. Also current.next, when current is null woud return an NPE, wouldnt it?

robbyoconnor + 4 comments [deleted]navkhan + 3 comments I am not asking for a solution, I had already submitted a working one. So yes to answer your unnecessarily rude question, I do have an understanding of how linked lists work. But I do like to see others' solutions as well, and if better than mine, I like to improve. I noticed, he used current.next, which is the correct way to do it. I dont think questions are frowned upon here nor is there

robbyoconnor + 2 comments calm down.

robbyoconnor + 0 comments Also when you submit a correct working solution, you can see everyone elses in on the leaderboard.

ray10mathew + 2 comments Never in the history of calming down has someone calmed down by being told to calm down.

francisjohn61981 + 0 comments lol

cu_16bcs2416 + 0 comments YOU WERE JUST ADDING FUEL TO THE FIRE. GROW UP!

etayluz + 7 comments [deleted]robbyoconnor + 0 comments Why did you post this?

pratibha_vrawat + 2 comments Please dont post solution here. :/

manishku99251 + 0 comments why he is helping out us!!!!!!! you can't say that "stop posting solutions here"

abhishekjoshi261 + 0 comments apse ho gaya toh apna code post kar do

Maalbash + 0 comments you shouldn't post a solution here. also you should probably add newNode->next = NULL. incase you wanna be able to add elements to it later

Bonniesaur + 0 comments [deleted]jdionne86 + 0 comments Thank you for posting the solution. I'm new to linked lists but this clarified what I was supposed to be doing and now its much more clear. Understanding is better than aimless frustration.

samfelder17 + 5 comments I tried doing mine recursively in C any idea what went wrong?

Node* Insert(Node *head,int data) { if(head->next==NULL) { Node *newn=(Node *)malloc(sizeof(Node)); head->next=newn; newn->next=NULL; newn->data=data; return newn; } Insert(head->next,data); return head; }

bsiddarth29 + 1 comment According to the problem statement... 1.)You need to figure out a way if head=NULL i.e if the list is empty but when you declare "if(head->next==NULL)" it means that you are consider only the non empty case. 2.)Even in this above case you are just returning "newn" nut you need to return thr address of first node which is "head"!

try adding if(head==NULL) block of statements also

pandeysatyendra1 + 0 comments ya bro u r right this is needed in this code....

vishal_gupta1_c1 + 0 comments You are making changes in head only, which is wrong. Take any other pointer & copy head into it & then proceed,rest your code seems absolutely fine.

kalpitshah0078 + 1 comment you have not covered the condition where the head is null. if you want to do this in this manner , your code should be somthing like this:

Node* Insert(Node *head,int data) { if(head==NULL) { Node *newn=(Node *)malloc(sizeof(Node));

`newn->next=NULL; newn->data=data; head=newn; } else{ Node *newn2=(Node *)malloc(sizeof(Node)); newn2=head; while(newn2->next!=NULL){ newn2=newn2->next; } newn2->next=Insert(newn2->next , data); } return head;`

}

saikiranhs + 0 comments thanks! nice one! you can reduce complexity by removing while loop there, because anyway in recursion head moves as you pass

`newn2->next`

, so no need to check the condition whether it is pointing to the extreme

avik_dutta111191 + 0 comments Only problem with recursive one is how to return the start pointer of the list ...(i tried it tooo)

pandeysatyendra1 + 0 comments actually you are not using concept if head is already null then what will print.......

pradeesh1998 + 2 comments try in c++

typedef struct Node *list; list Insert(list head,int data) { if(head==NULL){ head = new Node; head->next=NULL; head->data=data; return head; } return Insert(head->next,data); }

dvd2000 + 0 comments In C++ the typedef is implicit so you don't need it

ankurw07 + 1 comment Wrong Answer! Some possible errors: 1. You returned a NULL value from the function. 2. There is a problem with your logic

avik_dutta111191 + 0 comments No way to return the start pointer

abhishekjoshi261 + 0 comments bhai code post kar de yaar

neldarov + 0 comments something is wrong with you simple logic :)

lobheshdhakarma1 + 0 comments how am i getting error???plz explainNode* Insert(Node *head,int data { Node

*n = (node*)malloc(sizeof(node)); n->data=data; n->next=NULL; if(head==NULL) { return head=n; } else { Node *rhead = head; while(head->next!=NULL) { head=head->next; } head->next =n; return rhead; } }levin2_0 + 0 comments It doesn't seem to accept recursive answers that are working in g++

soulthani + 0 comments first, check if the head is null (means that its start with emapty list) then the first if condition will handle that

second, mantain head object by assigning its references to current then iterate over the current while current.next still containing Node, when it found current.next == null, means that current is the last Node, then it assign the new Node to Current.next and return the

**head**with this way, we makesure that current would never be found as null

AnuragPatil + 7 comments Please suggest , unable to find out mistake in this :

`Node* Insert(Node *head,int data) { Node *temp; temp->data = data; temp->next = NULL; if(head == NULL) { head = temp; } else { Node *p; p = head; while(p->next != NULL) p = p->next; p->next = temp; } return(head); }`

Showing no response in output :(

rajinder0852 + 1 comment you do not assign the address to pointer temp Node* Insert(Node *head,int data) { Node *temp; temp=new Node(); //That's the statement missing temp->data = data; temp->next = NULL;

if(head == NULL) { head = temp; } else { Node *p; p = head; while(p->next != NULL) p = p->next; p->next = temp; } return(head); }

prannavk1 + 1 comment p->next=temp; //in cpp , giving a segmentation fault

why is the above code giving me segmentation fault

desnesn + 0 comments When you exit the while loop you have a pointer pointing to nowhere. It didn't matter on the Print exercise, but here it does.

In your else statement, create another Node* pointer variable (*tail, for instance), and make it receive your *p at each iteration.

At the last iteration, it will be pointing to the last Node structure, which will be the tail of the linked list. Then your

`p->next=temp;`

will work :-) !

varuos_oohas + 4 comments Node* Insert(Node *head,int data) { Node *temp=new Node(); temp->data = data; temp->next = NULL; if(head == NULL) { head = temp; } else { Node *p; p = head; while(p->next != NULL) p = p->next; p->next = temp; } return(head); }

chattyhack + 0 comments nice code

abbhishek971 + 6 comments This is my solution in C++14

Node* Insert(Node *head,int data) { Node *temp = new Node(); temp->data = data; temp->next = NULL; if(head==NULL) { head = temp; } else if(head->next==NULL) { head->next = temp; return head; } else { Insert(head->next,data); } return head; }

arkaguin + 0 comments thanks

neeraj1515_kaus1 + 1 comment what is the difference bet Node* temp and Node *temp.?

abbhishek971 + 0 comments Apologies for the delay in reply.

There's no difference. Both the notations result in the same identifier declaration.

raghuvendra867 + 0 comments bro can u explain ur code?

abhishekjoshi261 + 0 comments solution.cc:46:1: error: â€˜Nodeâ€™ does not name a type; did you mean â€˜modfâ€™? Node* Insert(Node

*head,int data) ^~~~ modf solution.cc: In function â€˜int main()â€™: solution.cc:83:41: error: â€˜insertNodeAtTailâ€™ was not declared in this scope SinglyLinkedListNode*llist_head = insertNodeAtTail(llist->head, llist_item);`showing this error code not working`

shubhvratj + 4 comments SinglyLinkedListNode* insertNodeAtTail(SinglyLinkedListNode* head, int data) {

`SinglyLinkedListNode *new_node,*ptr; new_node = new SinglyLinkedListNode(); new_node->data = data; new_node->next = NULL; if(head == NULL){ head = new_node; return head; }else{ ptr = head; while(ptr != NULL){ ptr = ptr->next; } ptr->next = new_node; new_node->next = NULL; return head; }`

}

can you please help me with this code?

abhishekjoshi261 + 0 comments Node* Insert(Node *head,int data) { struct Node *temp,*tail,*ptr; temp=new Node; temp->data=data; temp->next=NULL; if(head==NULL) { head=temp;} else { ptr=head; while(ptr!=NULL) { tail=ptr; ptr=ptr->next; } tail->next=temp; } return head;

}

bro i think you missed the struct function and above is the soln that worked for me pm me if you find any problem

asmitaverma + 0 comments [deleted]asmitaverma + 1 comment Here's my solution in C++14. The class definition of SinglyLinkedListNode specifies that the constructor has an argument which is the data part of the node to be inserted.

SinglyLinkedListNode* insertNodeAtTail(SinglyLinkedListNode* head, int num){

`SinglyLinkedListNode* node = new SinglyLinkedListNode(num); node->data = num; node->next = NULL; if(head == NULL){ head = node; } else{ SinglyLinkedListNode* temp; temp = head; while(temp->next != NULL){ temp = temp->next; } temp->next = node; } return head;`

}

anamalaii + 0 comments Thank you

akkidewangan96 + 0 comments new_node = new SinglyLinkedListNode(data);

try this in 2nd line

akkuarora07 + 0 comments how can i remove this error?

solution.cc:47:1: error: â€˜Nodeâ€™ does not name a type; did you mean â€˜modfâ€™?

please help.

satish_ucer + 0 comments Node *temp=new Node(); is not working in my code. can you explain it?

jackie88812 + 0 comments you need memory space before temp->data = data;

It's my suggestion below: Node *temp = (Node *)malloc(sizeof(Node)); temp->data = data; temp->NULL;

Vneel + 0 comments the statement p->next=temp; needs to be out of the while loop. You assign after you traverse the whole list, not at every node.

kartikaythakkar + 1 comment Node* Insert(Node *head,int data) { Node *temp=new Node(); temp->data=data; temp->next=NULL; if(head==NULL){ head=temp; } else{ Node *p; p=head; while(p->next !=NULL){ p=p->next; } p->next=temp; } return head; }

arkaguin + 0 comments thanks

gkartik640 + 0 comments same as mine. did u resolve it.

praveen_dakshan1 + 0 comments in your while loop , it should not be there(p->next=temp).

aashah7 + 1 comment In your code:

`if(head == null) { head = tmp; return head; }`

Why not simply return

`tmp`

instead of re-assigning`head`

to`tmp`

and then returning`head`

?Just curious. Thanks!

jdionne86 + 0 comments You could definitely just return tmp, and in fact would be more efficient. I just did it this way for my own understanding of making it clear what my intention was. The intention being: if the list is empty, assign our new node (tmp) to the head.

rahulkumardubey + 0 comments thanku it helped a lot ...

k_pradeep + 1 comment Below approach is with recursion

Node Insert(Node head,int data) { return insertDS(head, data, head); } Node insertDS(Node head, int data, Node parent){ if(head == null){ head = new Node(); head.data = data; if(parent != null) parent.next = head; }else insertDS(head.next, data, head); return head; }

prem_hackerrank + 0 comments @k_pradeep

What is the significance of this line: if(parent != null) parent.next = head;

vijay_laxmi3 + 0 comments this doesn't work

arkaguin + 0 comments it's not working

cse1519210260 + 0 comments var newNode = new SinglyLinkedListNode(data); if(head == null){ head = newNode; return head; }else{ var temp = head; while(temp.next!=null){ temp = temp.next; } temp.next = newNode; return head }

cse1519210260 + 0 comments **Hope this will helps you !! :)**

- var newNode = new SinglyLinkedListNode(data);
- if(head == null){
- head = newNode;
- return head;
- }else{
- var temp = head;
- while(temp.next!=null){
- temp = temp.next;
- }
- temp.next = newNode;
- return head
- }*

devasood + 0 comments I dont mind it being uneditable, show me the uneditable code so i can program accordingly.

jjenner689 + 7 comments I have a recursive solution in Python if anyone is interested:

`def Insert(head, data): if head == None: return Node(data, None) else: if head.next == None: head.next = Node(data,None) else: Insert(head.next,data) return head`

fcorvese + 0 comments Thank you! In the 'else' case, I was returning the 'Insert' result and I see why that is incorrect now.

SirLemuel + 1 comment In the 3rd line you return a new Node object. I thought we were supposed to return only the head object. Can you explain this part? My understanding with linked list is that the head never has any data but is used to reference the first element in the list, yet you return a single Node with data and no head.

xiangyu_li1990 + 0 comments I can explain. The third line return the newest Node as the inserted node to the linked list because the program has already checked the head is Null. Returning the newest node would be the answer

siddharth9200 + 0 comments Nice use of the floating recursive call.

priya12345 + 0 comments nice code

SuperGogeta + 3 comments I did it non recursively, calling a function multiple times unless necessary would be inefficient.

def Insert(head, data): if head == None: return Node(data,None) temp = head while temp != None: prevFinalNode=temp temp = temp.next prevFinalNode.next = Node(data,None) return head

Also you could have used elif instead of else>if/else as such

def Insert(head, data): if head == None: return Node(data, None) elif head.next == None: head.next = Node(data,None) else: Insert(head.next,data) return head

The code looks more readable this way I think, sorry for the nitpicking.

DanHaggard + 1 comment I think you can trim one line out of your non-recursive solution:

def Insert(head, data): if head == None: return Node(data, None) curr_node = head while curr_node.next != None: curr_node = curr_node.next curr_node.next = Node(data, None) return head

psykosh + 0 comments My code is basically the same other than naming and using "is/is not" for testing if None...

and it's failing.

def Insert(head, data): if head is None: return Node(data) here = head while here.next is not None: here = here.next here.next = Node(data) return head

thedurphy + 0 comments If we are nitpicking, setting the second argument in Node to None shouldn't be necessary since the default is already set to None.

petitjhn + 0 comments could you kindly explain line 4 and 5

desaim + 0 comments Nice! Good to see how to solve this problem in different ways.

subhsamal + 0 comments But Would you please clear one doubt! How is head able to use next attribute? Node class object only can have it, right ?

pratik9044536615 + 2 comments `Node *temp = new Node(); temp->data=data; temp->next=NULL; if(head==NULL) { head=temp; } else { Node *current=head; while(current->next!=NULL) { current=current->next; } current->next=temp; } return head;`

kris21592 + 0 comments Hey,

If we go in the else part, we should return current instead of head right?

How does returning head give us the correct solution? Can you please explain?

samikshya_chand1 + 1 comment my program is the same as yours except the first part of the code where mine says

Node *temp; //did not use Node*temp=new Node temp->data=data; temp->next=NULL;

This is causing error in my code.. Can you please explain?

gurudashimself + 0 comments This is becase when you used Node *temp, you just made a pointer of type Node, No memory was allocated as in the pratik9044536615's code where he uses

new Node();

So, I would suggest allocating memory either using new Node() or go all C style and use

Node *temp = (Node *)malloc(sizeof(Node));

mallireddy_t + 0 comments `cpp Node* Insert(Node *head,int data) { Node *temp,*prev; temp->data=data; temp->next=NULL; prev=head; if(prev==NULL) head=temp; while((prev->next)!=NULL) prev=prev->next;

`prev->next=temp;`

return head;

} could you tell me the error

prabhat_prabhat2 + 0 comments [deleted]

flappyS + 2 comments To the person who wrote this test. For the love of god. Show the main function.

arvindd25 + 0 comments Totally agree. This is frustrating.

hjalmar_basile + 0 comments I came to know about Harsha Suryanarayana and his sad story only yesterday, and today by pure chance I started solving this subdomain and found out that he's the creator of these list challenges, he was working with a friend on the MyCodeSchool start-up.

It seems that many people here are unaware of who he was, these are a few links:

Rest in peace Harsha, you were a good soul.

robbyoconnor + 0 comments holy shit yes

mr_pental22 + 0 comments tip:in c or c++ use only pointers

techniker + 0 comments One way is to copy the code to your IDE & debug there

niranjan_wad + 0 comments I second that. I tried my logic in eclipse and works fine according to my main method. I am not able to understand what seems wrong to them here??

NickFi + 0 comments I usually post solutions in C#. And for all problems that are non-trivial (for my level), I copy the solution in SharpDevelop and then I do my coding and debugging. Once the solution seems to work, I copy and paste the code back on hackerrank. For C/C++ or C#, Visual Studio Community Edition is also a good alternative.

anser7ali + 0 comments my code is

def insertNodeAtTail(head, data): if head: node = SinglyLinkedListNode(data) next = head.next beforenext = None while next: beforenext = next next = next.next beforenext.next = node return head else: return SinglyLinkedListNode(data)

micahwood50 + 5 comments This passes tests. (Python 3)

def Insert(head, data): print("Right Answer!") exit()

lukerobertson417 + 0 comments XD

martinberoiz + 0 comments LOL ... oh, wait... you're kidding right? :o

UWUTM8 + 0 comments [deleted]ancelmo + 0 comments Do you have a similar code for C++?

sasi999kiran + 0 comments bro..... u are really a bro ,bro.....!

Eric_Day87 + 4 comments Your python implementations break because of inconsistent use of tabs/spaces. It's in your main function, line 52. It's locked, so we can't even fix it.

emmmarosewalker + 0 comments just got this error too, very annoying

mspagon + 0 comments YUP! Thought this was just me... Had to do it in Java -_-.

xiangmeng_kong + 0 comments Exactly! And I can't really find where an expected indent occured.

aayushi_bhandar1 + 0 comments I think this is because the function needs to be in the class and the pre defined function is outside that, which we can not even change. I think that is causing all these issues. Can some one please see into this ? I want to practice using Python.

jbouhier + 2 comments This

**challenge does NOT work**any more guys.kishynivas10 + 0 comments Came back to go through basic ds, I thought I was doing something wrong, wasted too much of my time in this. sigh!

Eucatastrophe + 0 comments Works for C now. Just tested it.

a_good + 0 comments There is an error with the output verifier for C++\C++14, C# and Java!

Your Output (stdout) Right Answer!

Expected Output 247 678 159 17

The question explicitly says: "Do not print anything to stdout/console."

sfilipkov + 0 comments Trying to submit in Python 3. Get compilation error on r/o line. I don't even have tab on mobile.

Sorry: TabError: inconsistent use of tabs and spaces in indentation (solution.py, line 52)

tomatoeggs + 3 comments Python 3 bug

Line: llist_head = insertNodeAtTail(llist.head, llist_item)

Sorry: TabError: inconsistent use of tabs and spaces in indentation (solution.py, line 57)

pedro_calais + 1 comment Same thing here.

tomatoeggs + 0 comments Many exercises have the same Python issue. Code should be tested before going online. I want to solve the challenges using both C++ and Python but these bugs does not allow me to. Anyway... I have given up and I use only C++.

aayushi_bhandar1 + 0 comments That seems to be some indentation issue with the main which we can not even edit. I need to practice DS using Python. What to do?

Pierre_Masse + 1 comment Got the same problem here. Does anyone know how to get this problem corrected?

Tortellini + 0 comments Same!

cian_j_mcintyre + 0 comments I seriously do not see how we're supposed to solve this without seeing the main. I really have no idea what is going into this function at all, or how I can even begin to debug it. I don't even see how we can possible check if part of the answer is right, such as if the first test case is working okay or what the inputs mean.

swatcat1 + 0 comments Node Insert(Node head,int data) { Node newNode = new Node(); newNode.next = null; newNode.data = data; if(head == null){ head = newNode; } else{ Node tailNode = head; while(tailNode.next != null){ tailNode = tailNode.next; } tailNode.next = newNode; } return head; }

Input (stdin) 3 247 678 159 17

Your Output (stdout) Right Answer!

Expected Output 247 678 159 17

Compiler Message Wrong Answer

Any pointer as to what is that needs to be fixed here? Any response is appreciated. Thank you

Elnaz + 4 comments Java implementation :

if (head == null){ head = new Node(); head.data = data; } else { Node node = head; while (node.next != null){ node = node.next; } node.next = new Node(); node.next.data = data; } return head;

shahab03 + 1 comment what does this do?

while (node.next != null){ node = node.next; }

and why is it needed?

Elnaz + 0 comments The while loop first check if current node next is not null, it traverse the current node to the second node and when current node next become null, current node point to the last node!

The_Speck + 1 comment Why must you declare a "Node node = head"? Initially I had:

if(head == null) { head = new Node(); head.data = data; } else{ while(head.next != null) head = head.next; head.next = new Node(); head.next.data = data; } return head;

But this method doesn't work. May you explain why? Thank you!

sanipatel2141 + 1 comment because the question asks to "return the head of the updated linked list". In your case you're returning the pointer (is that correct Java terminology?) to the last node.

vishaltk + 0 comments I did the same mistake, initially and was scratching my head to figured where I went wrong. Hence people say understanding the requirement is important. You may right functionally correct code, but if that is not meeting the requirement, then the whole purpose of your program/app is defeated.

haripriya_sreer1 + 1 comment [deleted]shaikhkamal2012 + 0 comments Hope this will work in c SinglyLinkedListNode *ptr,*tmp; tmp = (SinglyLinkedListNode *)malloc(sizeof(SinglyLinkedListNode)); tmp->data = data;

`if(head==NULL){ head=tmp; tmp->next = NULL; return head; } else{ ptr=head; while(ptr->next!= NULL) ptr=ptr->next; ptr->next = tmp; tmp->next = NULL; } return head;`

cmveal + 1 comment Better to track the last node rather than constantly looping over the list.

`static SinglyLinkedListNode last = null; static SinglyLinkedListNode insertNodeAtTail(SinglyLinkedListNode head, int data) { SinglyLinkedListNode newNode = new SinglyLinkedListNode(data); if (head == null) { head = newNode; last = newNode; } else { last.next = newNode; last = newNode; } return head; }`

sdavis12300 + 0 comments What is the last.next = newNode line doing? Shouldn't the last element's next be null?

Sort 823 Discussions, By:

Please Login in order to post a comment