I was completing a Hackerrank challenge involving addition of elements to a linked list and printing it.
The input is of this format: A set of integers, in which the first element gives the size and the rest are the components of the list.
I completed the challenge in Java, but I am not able to do it in C. Input of 4 2 3 4 1 should print 2 3 4 1, but this snippet that I coded is giving me 1 1 1 1 1 1 .... {truncated}
My approach: Declare a new struct temp of type Node (with the data input as data field, and NULL in next field), then iterate thorough the linked list with head as the starting point, and when it reaches the last element, change the next field of the last element to the address of the current element.
Code:
#include <stdlib.h>
#include <stdio.h>
typedef struct Node{
int data;
struct Node* next;
}Node;
Node* insert(Node *head,int data)
{
Node temp = {data, NULL} ;
if (head == NULL)
{ head =&temp;
return head;
}
else{
Node* current = head ;
while(current->next !=NULL)
current = current->next ;
current->next = &temp;
return head;
}
}
void display(Node *head)
{
Node *start=head;
while(start)
{
printf("%d ",start->data);
start=start->next;
}
}
int main()
{
int T,data;
scanf("%d",&T);
Node *head=NULL;
while(T-->0){
scanf("%d",&data);
head=insert(head,data);
}
display(head);
}