使用 strcmp() 插入函数

Insert Function using strcmp()

我正在尝试创建一个插入函数,但我不知道是否允许在参数中使用 char 字符串和节点。

这个有用吗?为什么不呢?

    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;

您必须 return 列表的新头部 return 值。如果插入一个节点,则必须为一个节点分配内存。不要忘记第一个节点的初始化成员prev和最后一个节点的成员link 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 ); 

另一种解决方案是在函数 insert:

中为参数 head 使用输入和输出参数
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 );