Advertisement
satishfrontenddev4

Untitled

Jan 5th, 2024
119
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2. Given only a reference to a node to be deleted in a singly linked list, implement a function to delete the given node. The given node is guaranteed to be neither the first, nor the last node.
  3.  
  4.  
  5. Note: The node to be deleted is not necessarily the exact middle node but is one of nodes that is not at the ends.
  6.  
  7.  
  8. Note: The input format will accept K, which denotes the position of the node to be deleted. However, in the function definition you’re given, you will not be given K. Instead, you’ll only have a pointer to the node to be deleted, and you have to use only that. You will not be able to use K. The challenge is to figure out how to delete this node without having a reference to the head of the linked list.
  9.  
  10. Input format
  11. First-line contains N, the number of elements in the linked list.
  12.  
  13. Next line contains N space-separated integers, elements of the linked list.
  14.  
  15. Next Line contains K, denotes the position of the node to be deleted.
  16.  
  17. Output format
  18. A list of N integers after deleting the Kth node.
  19.  
  20. Constraints
  21. 0 <= N <= 10^5
  22.  
  23. -10^9 <= value <= 10^9
  24.  
  25. 1 < K < N
  26.  
  27. Sample Input 1
  28. 5
  29.  
  30. 1 5 2 4 3
  31.  
  32. 3
  33.  
  34. Sample Output 1
  35. 1 5 4 3
  36.  
  37. Explanation 1
  38. The 3rd node containing 2 has been removed leading to 1 5 4 3.
  39. */
  40. /*
  41. class ListNode{
  42.     constructor(val){
  43.         this.val = val;
  44.         this.next = null;
  45.     }
  46. */
  47. /**
  48.  * @param {ListNode} node
  49.  * @return {void}
  50.  */
  51. function deleteGivenNode(node) {
  52.       let curr=node;
  53.       let prev=null;
  54.       // copy  data(value) of all incoming nodes into ints immediate previoud nodes respectively
  55.       while(curr.next!=null){
  56.             prev=curr;
  57.             curr.val=curr.next.val;
  58.             curr=curr.next;
  59.       }
  60.       if(curr.next==null){
  61.             prev.next=null;
  62.       }
  63.      
  64.       return;
  65.      
  66. }
  67.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement