关于设计堆栈的困惑
Confusion regarding designing stack
本文关键字:堆栈 更新时间:2023-10-16
我必须设计一个堆栈,以便与pop
, push
, isempty
, isfull
等常规操作一起,它还支持函数get_min()
,该函数返回堆栈中的minimum
元素。所有操作必须在O(1)
中。
我使用linked list
作为堆栈。在链表的每个节点中,我添加了一个特殊字段min
来存储堆栈中的最小值。下面是我的代码:
#include <iostream>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <limits.h>
using namespace std;
typedef struct node
{
int data, min;
struct node *next;
}node;
bool isempty(node *head)
{
return !head;
}
void display(node *head)
{
while(head)
{
cout<<head->data<<"-->";
head=head->next;
}
cout<<"n";
}
int get_min(node *head)
{
return head->min;
}
int peek(node *head)
{
if(isempty(head))
return INT_MIN;
return head->data;
}
void push(node **head_ref, int data)
{
node *new_node;
new_node=(node*)malloc(sizeof(node));
new_node->data=data;
if((*head_ref)==NULL || data <= get_min((*head_ref)))
{
new_node->min=data;
}
else
{
new_node->min=(*head_ref)->min;
}
new_node->next=(*head_ref);
(*head_ref)=new_node;
}
int pop(node **head_ref)
{
if(isempty((*head_ref)))
return INT_MIN;
int c=(*head_ref)->data;
node *temp=(*head_ref);
(*head_ref)=(*head_ref)->next;
free(temp);
return c;
}
int main()
{
node *head=NULL;
push(&head, 3);
push(&head, 0);
push(&head, 1);
display(head);
cout<<get_min(head);
return 0;
}
我想问我是否违反任何堆栈属性使用上述方法,或者它是一个正确的方式来设计一个堆栈?
这是正确的,但我的建议是,而不是存储每个条目的最小元素只是创建另一个堆栈&存储最小元素
现在在PUSH操作中,只比较新元素和最小数组中的顶部元素如果它是最小或相等的,就把它插入到新的堆栈中。
在执行POP操作时,只是检查您弹出的元素是否与最小堆栈中的顶部元素相同。如果是,则将最小堆栈中的元素与原始堆栈一起POP。
这将有助于节省我们的内存。
这个问题是我在carway的实习面试中被问到的
相关文章:
- 算法问题:查找从堆栈中弹出的所有序列
- 使用模板进行堆栈实现; "name followed by :: must be a class or namespace"
- Visual Studio(或任何其他工具)能否将地址解释为调用堆栈(boost上下文)的开头
- 为什么调用堆栈数组会导致内存泄漏
- gdb错误:Backtrace已停止:上一帧与此帧相同(堆栈已损坏?)
- 在 leetcode 上提交解决方案时出现堆栈缓冲区溢出错误
- 我的 int main() 中出现堆栈溢出错误
- 堆栈和队列是否像C++中的数组一样传递?
- 拥有映射的现代方法,该映射可以指向或引用已在堆栈上分配的不同类型的数据
- 为什么 STL 容器适配器堆栈中的 top 返回常量引用?
- 从堆栈分配的原始指针构造智能指针
- 在函数范围内在堆栈上分配的数组在离开函数时是否总是被释放?
- 堆栈中大小变量输入错误 (C++)
- 堆栈问题(平衡表达式问题集)
- C++ 在堆栈中包含多态属性的类对象存储
- 用于解析 win64 堆栈跟踪的命令行客户端(可以访问符号服务器)
- 在 C++ 中使用链表进行堆栈
- 变量周围的堆栈'...'已损坏
- 在 gtest 中初始化堆栈上的引用变量的隔离错误
- C++线程的可用堆栈大小