Advertisement
satishfrontenddev4

Untitled

Jan 5th, 2024
124
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2. Given a linked list, remove the Kth node from the end of the list and return its head.
  3.  
  4. Note: the given K will always be a valid node.
  5.  
  6. Input format
  7. There are three lines of input
  8.  
  9. First line contains N, the number of nodes in the linked list
  10.  
  11. Second line contains N integers, denoting the values of the linked list
  12.  
  13. Third line contains K, the node to be deleted from the end.
  14.  
  15. Output format
  16. Return the head of the LL after deleting the Kth node from the end.
  17.  
  18. Function definition
  19. You have to complete the given function. It accepts two arguments - the head of the linked list, and k. You have to return the head of the LL after making the necessary change.
  20.  
  21. Constraints
  22. 1 <= N<= 10^5
  23.  
  24. -10^9 <= value <= 10^9
  25.  
  26. 1 <= K <= N
  27.  
  28. Sample Input 1
  29. 5
  30.  
  31. 1 5 2 4 3
  32.  
  33. 2
  34.  
  35. Sample Output 1
  36. 1 5 2 3
  37.  
  38. Explanation 1
  39. The 2nd node from the end is 4, removing which, gives us 1 5 2 3
  40.  
  41. Sample Input 2
  42. 5
  43.  
  44. 3 1 3 2 4
  45.  
  46. 4
  47.  
  48. Sample Output 2
  49. 3 3 2 4
  50.  
  51. Explanation 2
  52. The 4th node from the end is 1, removing which, gives us 3 3 2 4
  53. */
  54.  
  55. /*
  56. class ListNode{
  57.     constructor(val){
  58.         this.val = val;
  59.         this.next = null;
  60.     }
  61. */
  62. /**
  63.  * @param {ListNode} head
  64.  * @param {number} k
  65.  * @return {ListNode}
  66.  */
  67. function deleteKthToLast(head, k) {
  68.       let kthfrombegin;
  69.       let length=0;
  70.       let curr=head;
  71.       let prev=null;
  72.       if(curr==null)
  73.        return head;
  74.       while(curr!=null){
  75.             length++;
  76.             curr=curr.next;
  77.       }
  78.       curr=head;
  79.       kthfrombegin=length-k+1;
  80.       let countOfNodes=1;
  81.       if(kthfrombegin==1)
  82.        return head.next;
  83.       while(curr!=null&&countOfNodes<kthfrombegin){
  84.             prev=curr;
  85.             curr=curr.next;
  86.             countOfNodes++;
  87.       }
  88.       prev.next=prev.next.next;
  89.       return head;
  90.      
  91.  
  92.  
  93. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement