思路:
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);
*/