【问题标题】:Pop consecutive items on a stack if value is the same如果值相同,则弹出堆栈上的连续项
【发布时间】:2018-12-09 13:47:55
【问题描述】:

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

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

【问题讨论】:

  • 我删除了递归标签 - 我猜你不想要递归解决方案,但如果是,请说明。

标签: c string stack


【解决方案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
}

请注意,如果您没有typedef,变量定义中也需要struct,我猜您没有,因为参数是这样定义的。如果名称是mallocd,您需要在释放堆栈节点之前释放它。

【讨论】:

    猜你喜欢
    • 2018-05-09
    • 1970-01-01
    • 1970-01-01
    • 2014-11-21
    • 2020-02-06
    • 1970-01-01
    • 2023-03-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多