Sending the node to the front of the linked list when key matches. C Language

I'm having issues trying to move a new node to the front when the key ZZZ is used. It ends up deleting the previous head. The output that I'm looking for is:

First input:   Second Input:              New Traverse:     Third Input:               New Traverse:
ABC            ABC                        DEF               DEF                        DEF
               DEF -> ZZZ key is used     ABC               ABC                        GHI
                                                            GHI -> DEF key is used     ABC
Destination *insertAfter ( Destination *head, Destination *node, char *key )
{
  struct Destination *roam = head;

  if (head == NULL)
  {
    printf( "IF HEAD = NULL\n");
    head = node;

    return head;
  }
  else
  {
    char zzz[4] = { 'Z','Z','Z','\0' };

    while ( ( ( *roam ).next ) == NULL)
    {

      if ( strcmp( zzz, key) == 0 )
      {
        printf( "KEY CHECKED OUT\n" );
        ( *roam ).next = roam;
        head = node;

        return head;
      }

      else if ( !strcmp( zzz, key) )
      {
        printf( " 1st ELSE IF LOOP\n" );
        ( *node ).next = head;
        head = node;

        return head;
      }

      else if ( !strcmp( ( ( *roam ).code ), key) )
      {
        printf( "2nd ELSE IF LOOP \n" );
        struct Destination* temp = NULL;

        if ( ( ( *roam ).next) != NULL)
        {
          temp = ( *roam ).next;
          ( *roam ).next = node;
          ( *node ).next = temp;
        }
        else
        {
          printf("inside the 2nd ELSE IF LOOP\n" );
          ( *roam ).next = node;
        }

          return head;
        }

      //  roam = ( *roam ).next;
      }
      // printf("OUT OF WHILE LOOP\n" );
      // ( *roam ).next = node;
      //
      // return head;
  }
}

1 answer

  • answered 2019-12-10 14:41 Anteino

    This question has been answered numerous times on different website since it's such a general question. Please visit this link and scroll down. You will see the procedure to add an element to the head of a linked list is as follows:

    typedef struct node {
        int val;
        struct node * next;
    } node_t;
    
    ...
    
    void push(node_t ** head, int val) {
        node_t * new_node;
        new_node = malloc(sizeof(node_t));
    
        new_node->val = val;
        new_node->next = *head;
        *head = new_node;
    }
    

    You can then call the push function based on the condition you described.