关于设计堆栈的困惑

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的实习面试中被问到的