## Insert a Node at the Tail of a Linked List

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

- RK
ravi1008Asked to answer + 5 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 + 7 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;`

}

- NK
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]- NK
navkhan + 2 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 + 1 comment Never in the history of calming down has someone calmed down by being told to calm down.

- FJ
francisjohn61981 + 0 comments lol

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

pratibha_vrawat + 1 comment Please dont post solution here. :/

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

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.

- SF
samfelder17 + 4 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 + 0 comments 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

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

- AD
kalpitshah0078 + 0 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;`

}

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

- PG
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

- AW
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

- AD
avik_dutta111191 + 0 comments No way to return the start pointer

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

- LD
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 + 5 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); }

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

why is the above code giving me segmentation fault

- DA
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 :-) !

- SK
varuos_oohas + 3 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); }

- SK
- CR
chattyhack + 0 comments nice code

abbhishek971 + 2 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

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

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;

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

- KT
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

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

- PK
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; }

- PK
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

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`

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

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

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

- PS
priya12345 + 0 comments nice code

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

- D
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

- PK
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

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

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

- MD
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));

- MT
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

- SH
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

- NW
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??

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

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

lukerobertson417 + 0 comments XD

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

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

- AG
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."

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

- PS
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

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

Elnaz + 3 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;

- SN
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!

- AP
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!

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

- VN
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 + 0 comments [deleted]

lovinjv + 0 comments i donot understand the input here 3 247 678 159 17

and expected output : 247 678 159 17 although my code works fine in my local machine.,

- EW
bonjour + 2 comments python 3 recursion

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

- A
akinakillioglu + 0 comments [deleted] jinkp + 0 comments To condense it even further:

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

Black_Jack + 3 comments Can anybody help me with this. Node Insert(Node head,int data) { if(head==null){ Node head1=new Node(); head=head1; head.data=data; return head; } else{ Node node=new Node(); Node temp=head; while(temp!=null){ temp=temp.next; } temp=node; temp.next=null; temp.data=data; return head; } }

Kartik1607 + 2 comments when

`head == null`

, you are not setting`head.next = null`

Black_Jack + 0 comments Thanks for the answer. It really poped all testcases green.

adelin_ghanayem + 0 comments isn't it null by default ?

PRASHANTB1984 + 0 comments explanation and visual in this tutorial might help. Though you may need to translate the C code to Java since that is what you're using.

- AK
arunkumar_123 + 1 comment I was doing same mistake earlier by not handling the use case when head pointer of linked list is NULL. This is one of the sample test case. So, when head pointer is null then we have to set head pointer to the new linked list node.

if (head == null){ head = new Node(); head.data = data; }

Adding above if statement solved my problem. Im general, we just have to traverse the linked list and add a new node after tail node of linked list.- DK
debanjana_karma1 + 0 comments Node* Insert(Node *head,int data) { if(head==NULL) {

head->data=data; head->next=NULL; } else { Node *p=head; while(p->next!=NULL) { p=p->next; }`Node *x=new Node; x->data=data; x->next=NULL; p->next=x; }`

cout<<"Right Answer!"; return head; }

Can anyone please say what I should change in this code to avoid segmentation error?

Sort 584 Discussions, By:

Please Login in order to post a comment