Search code examples
cstringlinked-listnodesstrcmp

Insert Function using strcmp()


I'm trying to make an insert function, but I don't know if I'm allowed to used a char string and a node in the argument.

Does this work? Why not?

    void insert(char* str, node* head) {
      if (head == NULL) {
        node* new_node = malloc(sizeof(struct node));
        assert(new_node != NULL);
        new_node->value = strdup(str);
    }
    while (head != NULL) {
      if (strcmp(str, head->value)) {
        node *new_node = malloc(sizeof(struc node));
        assert(new_node != NULL);
        new_node->link = head;
        new_node->value - strdup(str);
      }
    }
    node *prev = head;
    head = head->link;

Solution

  • You havet to return the new head of the list by return value. If you insert one node you have to allocate memory for one node. Don't forget the initialize member prev of the first node and the member link of the last node with NULL:

    node* insert(char* str, node* head)
    {
        node* new_node = malloc(sizeof(struct node));
        assert(new_node != NULL);
        new_node->value = strdup(str);
        new_node->link = NULL;          // successor of new node is NULL
    
        if ( head == NULL )
        {
            new_node->pev = NULL;       // prdecessor of first node is NULL
            head = new_node;   
            return new_node;            // head was NULL, return new head
        }
    
        node *lastNode = head;          // go to last node of list
        while ( head->link != NULL )
            lastNode = lastNode->link;  // step one forward
    
        lastNode->link = new_node;      // successor of last node is new node
        new_node->prev = lastNode;      // predecesor of new node is last node
        return head;
    }
    

    -

    node *head = NULL;
    head = insert( "abc", head );
    head = insert( "def", head ); 
    

    An other solution would be to use an in and output paramter for your paramter head in function insert:

    void insert(char* str, node** head)
                            // ^^ in and output parameter
    {
      node* new_node = malloc(sizeof(struct node));
      assert(new_node != NULL);
      new_node->value = strdup(str);
      new_node->link = NULL;          // successor of new node is NULL
    
      node* prev = NULL;
      node* act = *head;
      while ( act != NULL )           // go to last node in list
      {
          prev = act;
          act = act->link;            // step one forward
      }
    
      new_node->prev = prev;     // predecessor of new node is last node or NULL
      if ( prev == NULL )
          *head = new_node;      // new node is the first node in list,
                                 //   write the new node back to head
      else
          prev->link = new_node; // successor of last node is new node
    }
    

    -

    node *head = NULL;
    insert( "abc", &head );
    insert( "def", &head );