Given a key (or data) to be inserted into the linked list of size N. The task is to insert the element at head or tail of the linked list depending on the input just before it p. If p is 0, then insert the element at beginning else insert at end.

Hint : When inserting at the end, make sure that you handle NULL explicitly.

Input Format:
First line of input contains number of testcases T. For each testcase, first line of input contains length of linked list N and next line contains 2*N integers, each element to be inserted into the list is preceded by a 0 or 1 which decide the place to be inserted.

Output Format:
For each testcase, there will be a single line of output which contains the linked list elements.

Your Task:
This is a function problem. You only need to complete the functions insertAtBeginning and insertAtEnd that returns head after successful insertion. The printing is done automatically by the driver code.

1 <= T <= 100
1 <= N <= 103


9 0 5 1 6 1 2 0 5 0
5 1 6 1 9 1
15 0 36 0 95 0 14 0

5 2 9 5 6
5 6 9
14 95 36 15

Testcase 1:
After inserting the elements at required position, we have linked list as 5, 2, 9, 5, 6.


** For More Input/Output Examples Use 'Expected Output' option **

Contributor: Harshit Sidhwa
Author: harshitsidhwa

If you have purchased any course from GeeksforGeeks then please ask your doubt on course discussion forum. You will get quick replies from GFG Moderators there.

Need help with your code? Please use, generate link and share the link here.

to report an issue on this page.