常用堆栈操作

来源:互联网 发布:js array 编辑:程序博客网 时间:2024/05/16 10:57
// 入栈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,同时将值放入valbool 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;    }}
0 0