# Insert a Node at the Tail of a Linked List

# Insert a Node at the Tail of a Linked List

devasood + 10 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 + 12 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 + 4 comments Never in the history of calming down has someone calmed down by being told to calm down.

francisjohn61981 + 0 comments lol

cu_16bcs2416 + 1 comment YOU WERE JUST ADDING FUEL TO THE FIRE. GROW UP!

sameeraktz + 0 comments dont

snehalparab83 + 0 comments perfect

avloknathreddy11 + 1 comment hahahahahahahahah

prashant_pundhir + 0 comments Adding solution in Java:

static SinglyLinkedListNode insertNodeAtTail(SinglyLinkedListNode head, int data) { SinglyLinkedListNode temp = new SinglyLinkedListNode(data);

`if(head==null) return temp; SinglyLinkedListNode current = head; while(current.next!=null) current = current.next; current.next = temp; return head; }`

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 + 6 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

strangerHash + 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 + 3 comments 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 extremethanhhienm3 + 0 comments Thanks ! your solution is good for me. I can undertant .

kunasinduja1998 + 0 comments can someone explain me the else condition;)

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

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

naimamunir_17 + 0 comments Urgent help needed. My code is constantly showing segmentation fault. Please help. Here is code:

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

SinglyLinkedListNode* temp; temp=head; SinglyLinkedListNode* new_node = (SinglyLinkedListNode*)malloc(sizeof (SinglyLinkedListNode));

if(head==NULL) { new_node->data=data; new_node->next=NULL; head=new_node; return head; }

else {

while(temp!=NULL) {temp=temp->next;}

temp->next=new_node;

new_node->next=NULL; new_node->data=data;

temp=head;

while(temp!=NULL) { printf("%d/n",temp->data); temp=temp->next; }

} return head;

}

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 + 1 comment 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

surveshjha20 + 1 comment Can you please check what is the problem with this?

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

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

}

sanskriti_gupta1 + 0 comments temp is not initialized

AnuragPatil + 9 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); }

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

why is the above code giving me segmentation fault

KuboK + 0 comments pointer temp needs to have assigned an adress

Node *temp=new Node();

Sahilamin219 + 0 comments try making p->next=temp statement out side of the while loop . it should not affect the result anyway.

chattyhack + 0 comments nice code

abbhishek971 + 8 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 + 6 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 + 4 comments 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

alexey_chekhovi1 + 0 comments SinglyLinkedListNode* node = new SinglyLinkedListNode(num);

Works.

SinglyLinkedListNode *newNode = new SinglyLinkedListNode();

solution.cc:61:62: error: no matching function for call to â€˜SinglyLinkedListNode::SinglyLinkedListNode()

So we do not have an empty constructor, but do have a constructor with parameters. The one who wrote the background of this task should be immediately exterminated.

omagrawal1207 + 0 comments I did the same but missed head == NULL part Thanks

NSVR57 + 0 comments we are not updating head with lastnode but we do only temp. how head is updating automatically?

[deleted] + 0 comments new_node = new SinglyLinkedListNode(data);

try this in 2nd line

sanket_sonje99 + 0 comments [deleted]sanket_sonje99 + 0 comments SinglyLinkedListNode *new_node = new SinglyLinkedListNode(data); new_node->data = data; new_node->next = NULL;

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

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.

ashish21ghosh + 0 comments I don't think you need to check if head->next==NULL, rather in the else block you can add

head->next = Insert(head->next,data);

vidushic0 + 0 comments you are genius

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

jagadishprasad31 + 0 comments there in the question the class name is SinglyLinkedListNode so

SinglyLinkedListNode temp=new Node();

`this is in java`

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).

dark_c_03 + 0 comments you have to create new node and allocate memory to it by malloc or new in c++

vnaykanswal55 + 0 comments Do dynamic memory allocation C++ Node* temp=new Node(); C Node* temp= (Node*)malloc(sizeof(Node));

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
- }*

agarwal_shivam23 + 0 comments i am not getting Node insert() method .we have just created the class node and now we are creating node insert method .can you help out.

akhilsharma_as82 + 0 comments how come u are returning head everytime, it shud be return current; head will only be returned in if condition

adarsh2dubey + 0 comments can anyone tell me why it return alll elemnt in linkedlist while we just return head ???

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

jjenner689 + 10 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 ?

ritikagupta8734 + 0 comments why u returned head ? in last line u can return head.next ?

vineethngr + 0 comments can u send the python 3 answer because iam new to linked lists

krsanu555 + 0 comments @jjenner689 For some test cases, your code giving this error:-RecursionError: maximum recursion depth exceeded

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)

abhimanyuaj001 + 0 comments full answer

class Node: def __init__(self,data): self.data=data self.next=None class SinglyLinkedList: def __init__(self): self.head=None def insertNodeAtTail(head, data): node = Node(data) if head==None: head=node else: cur=head while cur.next: cur=cur.next cur.next=node return head

yacharenikrish + 1 comment **Java Solution: Maintain tail node while traversing from head and at the end assign new node.**static SinglyLinkedListNode insertNodeAtTail(SinglyLinkedListNode head, int data) { SinglyLinkedListNode nn = new SinglyLinkedListNode(data); if(head == null) { return nn; } else { SinglyLinkedListNode temp = head, prev = null; while(temp != null) { prev = temp; temp = temp.next; } prev.next = nn; return head; } }

nivethapriya2000 + 1 comment [deleted]nivethapriya2000 + 0 comments why u r using prev ?

micahwood50 + 6 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.....!

[deleted] + 0 comments [deleted]

jbouhier + 3 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.

VEGAYED + 0 comments Works for Java 8. in java idk other languajes you need return the head

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.

Sort 1164 Discussions, By:

Please Login in order to post a comment