why my code shows time limit exceeded?
#include
using namespace std;
class node
{
public:
int data;
node *next;
node(int d)
{
data = d;
next = NULL;
}
};
void insert_end(node *&head, int d)
{
if (head == NULL)
{
head = new node(d);
return;
}
else
{
node *tail = head;
while (tail->next != NULL)
{
tail = tail->next;
}
tail->next = new node(d);
return;
}
}
node *input()
{
int d;
node *head = NULL;
cin >> d;
while (d != -1)
{
insert_end(head, d);
cin >> d;
}
return head;
}
void print(node *head)
{
while (head != NULL)
{
cout << head->data << " ";
head = head->next;
}
}
node *knode(node *head, int k)
{
int c = 0;
node *slow = head;
node *fast = head;
while (c < k)
{
fast = fast->next;
c++;
}
while (fast != NULL)
{
fast = fast->next;
slow = slow->next;
}
return slow;
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int k;
node *head = input();
cin >> k;
node *s = knode(head, k);
cout << s->data;
return 0;
}