I'm given a sequence of integers. The length of the sequence is unknown but the sequence ends with a -1. I'm given another number pos . I want to output the integer in position pos. If pos > length of the sequence output -1.
I'm told to implement two functions :
Node loadNum(): Function to load the numbers onto the linked list & Return a pointer to the head of the list
void releaseMem(Node head): Function to release the memory after every iteration
I've written following code:
#include <stdio.h>
#include <stdlib.h>
struct node{
int data;
struct node* next;
};
typedef struct node* Node;
Node loadNum();
void printNum(Node head,int pos)
{
int i = 1;
Node temp = head;
while( i != pos ){
temp = temp->next;
if( temp == NULL){
printf("-1");
return;
}
i++;
}
printf("%d",temp->data);
}
void releaseMem(Node head);
int main()
{
int i,T;
int pos;
Node head;
scanf("%d",&T);
for (i = 0; i < T; i++){
head = loadNum();
scanf("%d",&pos);
printNum(head, pos);
if(i<t-1)>
printf("\n"); releaseMem(head);
}
return 0;
}
Node loadNum()
{
Node temp=NULL,head=NULL;
int n;
scanf("%d",&n);
if(n!=-1)
{
temp=(Node)malloc(sizeof(struct node));
head=temp;
}
while(n!=-1)
{
temp->data=n;
temp->next=(Node)malloc(sizeof(struct node));
temp=temp->next;
scanf("%d",&n);
}
temp=NULL;
return head;
}
void releaseMem(Node head)
{
Node temp;
while(head!=NULL)
{
temp=head;
head=head->next;
free(temp);
}
}
input/Output should be like this:
Input:
2
9 8 5 2 ‐1
4
5 3 1 9 10 ‐1
9
output:
2
‐1
Program provides correct output except for few test cases which is showing
"time limit exceeded" for given input:-
input:
3
5 4 1 3 5 ‐1
5
2 3 6 7 ‐1
4
6 3 4 3 8 ‐1
2
Where am I going wrong?