The prev -curr way


  • 0
    S

    I have done this in the traditional prev-curr way, where I check if the value of the current node is equal to the desired value, if it is, then I simply point the next of the current node to the next of the current node.
    I then update the value of my prev to my current and the value of my current to the value of my next.
    There are a few corner cases here:

    1. if you have only one node --> in this case, the head should start pointing to the next of the curr node which is null, but the prev does not get updated
    2. if you are deleting the last node or the middle node, your code should take care of it.
    3. If you have only 2 nodes, but with the value to be deleted, take care that your updates of prev and current are handled properly.
      ,,,
      class Solution {
      public ListNode removeElements(ListNode head, int val) {
      ListNode prev = null;
      ListNode curr = head;
      while(curr!=null){
      if(curr.val==val){
      if(prev==null){
      head =curr.next;
      }
      else{
      prev.next = curr.next;
      }
      curr = curr.next;
      }
      else{
      prev = curr;
      curr = curr.next;
      }
      }
      return head;
      }
      } '''

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.