常用堆栈操作

// 入栈
void push(struct ListNode** head, int val)
{
    struct ListNode* cur = *head;
    struct ListNode* pushnode = (struct ListNode*)malloc(sizeof(struct ListNode));
    pushnode->val = val;
    pushnode->next = NULL;

    if (*head == NULL)
    {
        *head = pushnode;
    }
    else
    {
        while(cur->next != NULL)
        {
            cur = cur->next;
        }
        cur->next = pushnode;
    }
}

// 出栈,栈为空则返回false;否则为true,同时将值放入val
bool pop(struct ListNode** head, int* val)
{
    struct ListNode* cur = *head;
    struct ListNode* pre = NULL;

    if (*head == NULL)
    {
        return false;
    }
    else
    {
        while(cur->next != NULL)
        {
            pre = cur;
            cur = cur->next;
        }

        *val = cur->val;
        if (*head == cur)
        {
            *head = NULL;
        }
        else
        {
            pre->next = NULL;
        }
        free(cur);
        return true;
    }
}

// 取得栈顶
bool top(struct ListNode* head, int* val)
{
    struct ListNode* cur = head;

    if (head == NULL)
    {
        return false;
    }
    else
    {
        while(cur->next != NULL)
        {
            cur = cur->next;
        }
        *val = cur->val;
        return true;
    }
}

// 元素总个数
int count(struct ListNode* head)
{
    int count = 0;
    struct ListNode* cur = head; 

    if (head == NULL)
    {
        return 0;
    }
    else
    {
        while(cur != NULL)
        {
            ++count;
            cur = cur->next;
        }
        return count;
    }
}

// 清理栈
void clearnode(struct ListNode** head)
{
    struct ListNode* cur = *head; 
    struct ListNode* temp = NULL; 

    while(cur != NULL)
    {
        temp = cur->next;
        free(cur);
        cur = temp;
    }
    *head = NULL;
}

// 给定输入序列A,里面的数字依次为1~N,用户自定义堆栈S,每一次进行对战的入栈或出栈操作,出栈的元素形成序列B。
// 给定输出序列B,判断是否合法。
bool is_valid_output(int* output, int N)
{
    int outval = 0, val = 1, len = N;
    int inval = 0;
    struct ListNode* OutputNode = NULL;

    if (N <= 0)
    {
        return false;
    }
    else
    {
        while(len--)
        {
            outval = *output;

            while (val <= outval && val <= N)
            {
                    push(&OutputNode, val);
                    ++val;
            }

            pop(&OutputNode, &inval);

            if (inval == outval)
            {
                return false;
            }
            ++output;   
        }
        return true;
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值