1

我正在制作这个链接(上面的代码),我需要当信息(国家)与以前的信息相同时,链接列表只更新计数并且不存储信息示例

如果有这个输入

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;
}
4

2 回答 2

0
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;
}
于 2012-04-26T10:57:34.977 回答
0

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

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

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

if(strcmp(curNode->data,bookings->country)==0){
        curNode->count++;
        free newNode;
        return;
}
于 2012-04-26T10:41:42.613 回答