C - 链表打印



im 使这个链接(上面的代码),我需要当信息(国家)与之前的信息相同时,链表仅更新计数,并且不存储信息示例

如果有此输入

mmm 1
mmm 2
mmm 3

输出需要mmm3

我应该怎么做才能做到这一点

void insertitem(ListNode **startPtr,booking_type* bookings){
    int ans=0;
    ListNode *prevNode =NULL ,*curNode=*startPtr;
    ListNode *newNode = (ListNode*)malloc(sizeof(ListNode));
    strcpy(newNode->data, bookings->country); //newNode->data =bookings->country;
    newNode->nextPtr = NULL;
    newNode->count = 1;  
    while ((curNode!=NULL)&&(strcmp(curNode->data,bookings->country)<=0) ) // future : use strcmp 
    {
      if(strcmp(curNode->data,bookings->country)==0){
        newNode->count++;
      }
      prevNode=curNode;
      curNode = prevNode->nextPtr;
    }
    if(prevNode == NULL)
        *startPtr=newNode;
    else
        prevNode->nextPtr = newNode;
    newNode->nextPtr = curNode;
}

当您看到有一个具有相同国家/地区的 LL 节点时,您当前正在增加新节点的计数:

if(strcmp(curNode->data,bookings->country)==0){
        newNode->count++;
}

相反,您可以做的是增加现有节点的计数。同样在这种情况下,您不会插入新节点,因此您需要释放错误定位的节点并从函数返回:

if(strcmp(curNode->data,bookings->country)==0){
        curNode->count++;
        free newNode;
        return;
}
void insertitem(ListNode **startPtr,booking_type* bookings){
    int dif;
    ListNode *curNode. *newNode;

    for (dif = -1; (curNode= *startPtr); startPtr = &curNode->nextPtr ) {
      dif = strcmp(curNode->data,bookings->country);
      if (dif==0) {
          /* found it! we're almost done */
          curNode->count += 1;
          return; }
      if (dif > 0) break; 
    }
    /* when we get here, startPtr points to the pointer where we should
    ** insert our new node.
    ** *ptr becomes our tail, and ptr should point at the new node
    */
    newNode = malloc(sizeof *newNode);
        /* TODO: check for malloc() failure here ... */
    strcpy(newNode->data, bookings->country);
    newNode->nextPtr = *startPtr;
    newNode->count = 1;  
    *startPtr=newNode;
    return;
}

相关内容

  • 没有找到相关文章

最新更新