// 入栈
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;
}
}
常用堆栈操作
最新推荐文章于 2025-06-18 16:41:11 发布