How to approach this problem
https://hack.codingblocks.com/app/contests/1617/1100/problem
Linkedlist kth append
iterate n-k+1 times then, you find the head of the required linkedlist,store them in an array then append them in the front of the linkedlist
@sheikhhaji18 think this way if you have any linked list then you keep two pointers lets suppose fast and the next and then if you have to append the last k elements at the top:
okay then i should explain you with the help of the example:
lets take the sample case:
7
1 2 2 1 8 5 6
3
in this we move the first pointer of the 2 pointers to iterate the list and we move the first pointer to the next for k times and then the pointer fast have traversed this lineked list till (1 2 3 ):
and slow is at 1 only then we will run both simultaneouly till fast reaches the end.
we can declare any other node as well so that it can be keep the record of the slow say prev(node).
then when the fast is at the end then we can connect the end to the head.
and the prev keeping record of slow will be at: 1 2 2 1
and after this we will attach null.
and our head will slow i.e 8.
so the linked list will become:
8561221
Here for your referece i am attaching the code:
if you have any doubt you can ask here:
Happy Learning!!
by using array you are using extra space which is not required.
Happy Learning!!
it’s like kth element from the last of linked list
@sheikhhaji18 yes right.
if you feel that your doubt is resolved.
you can mark this as resolved.
Happy Learning!!
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.