2012-04-26 84 views
1

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; 
} 
+2

对不起,你必须解释你想要一点什么更好;这对我没有意义。 – trojanfoe 2012-04-26 10:38:13

+0

你得到的错误输出是什么? – huon 2012-04-26 10:38:31

+0

换句话说,我需要的是,当国家的信息与前一个存储在链表中的信息相同时,只有计数会被更新。 – user1312254 2012-04-26 10:40:42

回答

0

当你看到有有有同一个国家,当前正在增加新节点的计数LL节点:

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

相反,你可以做的是增加了已经存在的数节点。在这种情况下,你会不会被插入新的节点,所以你需要释放malloced节点,并从函数返回:

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

但我需要增加这个代码的计数,当我添加到我的代码计数是留给1 – user1312254 2012-04-26 10:43:50

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; 
} 
+0

但这里发生了什么? – user1312254 2012-04-26 11:01:07

+0

* startPtr = newNode;在说undefined – user1312254 2012-04-26 11:07:13

+0

我把代码缩小到(几乎)最小。还有进一步减少的可能性:你可以删除curNode变量......也许我在变量名中做了一些错字,我对CamelCase并不擅长。 – wildplasser 2012-04-26 11:08:40