leetcode:栈排序(使栈顶为最小的值)

思路:
1.使用双向链表进行栈的模拟。
2.每次入栈都与当前栈中元素按栈顶依次进行比较,然后插入到合适的位置。

typedef struct
{
    int val;
    struct Node *next;
    struct Node *previous;
}Node;

typedef struct 
{
    Node *head;
    Node *current;//指向栈顶的指针
} SortedStack;


SortedStack* sortedStackCreate() 
{
    SortedStack *s = (SortedStack*)malloc(sizeof(SortedStack));
    if(s == NULL)
        return NULL;
    s->head = (Node*)malloc(sizeof(Node));

    s->head->next = NULL;
    s->head->previous = NULL;
    s->current = s->head;//初始状态栈顶和头指针重合

    return s;
}

void sortedStackPush(SortedStack* obj, int val) 
{
    Node *temp0 = NULL;
    Node *temp1 = NULL;
    Node *t = NULL;

    if(obj == NULL)
        return;

	//分配节点空间
    temp0 = (Node*)malloc(sizeof(Node));
    temp0->val = val;
    temp0->next = NULL;

    temp1 = obj->current;
    //查找到合适的插入位置
    while(temp1 != obj->head && val > temp1->val)
        temp1 = temp1->previous;
    
    temp0->previous = temp1;
    temp0->next = temp1->next;
    temp1->next = temp0;
    //若为第一个入栈的元素则不执行下述语句
    if(temp0->next != NULL)
    {
        t = temp0->next;
        t->previous = temp0;
    }
    
    //根据插入位置情况更新栈顶指针
    if(obj->current->next == temp0)
        obj->current = temp0;
}

void sortedStackPop(SortedStack* obj) 
{
    Node *temp = NULL;
    if(obj == NULL)
        return;
    if(obj->current == obj->head)
        return;
    temp = obj->current;
    obj->current = temp->previous;
    obj->current->next = NULL;//重要:将栈顶的next置空
    free(temp);
}

int sortedStackPeek(SortedStack* obj) 
{
    if(obj == NULL)
        return -1;
    if(obj->current == obj->head)
        return -1;
    return obj->current->val;
}

bool sortedStackIsEmpty(SortedStack* obj) 
{
    if(obj->current == obj->head)
        return true;
    else
        return false;
}

void sortedStackFree(SortedStack* obj) 
{
	//释放分配的节点与初始分配的栈结构体
    Node *temp0 = NULL;
    Node *temp1 = NULL;
    if(obj == NULL)
        return;
    temp0 = obj->head;
    while(temp0 != obj->current)
    {
        temp1 = temp0;
        temp0 = temp1->next;
        free(temp1);
    }
    free(temp0);
    free(obj);
}

/**
 * Your SortedStack struct will be instantiated and called as such:
 * SortedStack* obj = sortedStackCreate();
 * sortedStackPush(obj, val);
 
 * sortedStackPop(obj);
 
 * int param_3 = sortedStackPeek(obj);
 
 * bool param_4 = sortedStackIsEmpty(obj);
 
 * sortedStackFree(obj);
*/
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值