如果值相同,则将连续项弹出堆栈

时间:2018-06-30 18:16:53

标签: c string stack pop

对于我的程序,我有一堆字符串,并且试图在顶部弹出该值,但是如果栈上的下一个字符串具有相同的名称,我也想将该字符串也弹出,依此类推,直到所有上面那个名字的人不见了。我可能正在屠杀实施方案,所以有人可以指导我正确的方向吗?

char *dropoff(struct stack *tosPtr)
{
    printf("current tos is %s\n", tosPtr->name);
    if(tosPtr == NULL)
        return STACK_IS_EMPTY;
    while(strcmp(tosPtr->name, tosPtr->next->name) == 0) {
        stack *oldBox = tosPtr;     
        tosPtr = tosPtr->next;          
        if(oldBox == tosPtr)
            tosPtr = NULL;
        free(oldBox);
    }

    return tosPtr;
}

1 个答案:

答案 0 :(得分:1)

看起来您很近。您忘记删除第一个单词(无论您声明要执行此操作)。然后您的那一刻快到了。另外,您正在比较两个应该始终不相等的指针(tosPtrtosPtr->next)-除非应该有一些您未提及的循环引用?

struct stack *dropoff(struct stack *tosPtr) {
    printf("current tos is %s\n", tosPtr->name);
    if(tosPtr == NULL)
        return STACK_IS_EMPTY;

    struct stack *oldBox = tosPtr;
    tosPtr = tosPtr->next;
    //Double check in while we didn't hit bottom of stack
    while(tosPtr && strcmp(oldBox->name, tosPtr->name) == 0) {
        free(oldBox); //Maybe need to free oldBox->name as well?!
        oldBox = tosPtr;
        tosPtr = tosPtr->next;
    }
    //One node left to free - maybe name?
    free(oldBox);
    return tosPtr ? tosPtr : STACK_IS_EMPTY; //Return empty stack if needed
}

请注意,如果您没有struct,也需要在变量定义中使用typedef,而且我猜您也没有,因为参数是用这种方式定义的。如果名称是malloc d,则在释放堆栈节点之前就需要释放它。