程序员面试金典-0305-栈排序
这个题目一直没pass,是因为测试数据有相同的数据,需要注意。
栈排序。 编写程序,对栈进行排序使最小元素位于栈顶。最多只能使用一个其他的临时栈存放数据,但不得将元素复制到别的数据结构(如数组)中。该栈支持如下操作:push、pop、peek 和 isEmpty。当栈为空时,peek 返回 -1。
示例1:
输入:
["SortedStack", "push", "push", "peek", "pop", "peek"]
[[], [1], [2], [], [], []]
输出:
[null,null,null,1,null,2]
示例2:
输入:
["SortedStack", "pop", "pop", "push", "pop", "isEmpty"]
[[], [], [], [1], [], []]
输出:
[null,null,null,null,null,true]
struct list_node{
int data;
struct list_node * next;
};
typedef struct {
struct list_node * head;
} SortedStack;
bool sortedStackIsEmpty(SortedStack * obj);
struct list_node * node_init(int val){
struct list_node * t = malloc(sizeof(struct list_node));
t->data = val;
t->next = NULL;
return t;
}
SortedStack* sortedStackCreate() {
SortedStack * s = malloc(sizeof(SortedStack));
struct list_node * h = node_init(-1);
s->head = h;
return s;
}
void sortedStackPush(SortedStack* obj, int val) {
struct list_node * h = obj->head;
struct list_node * temp = node_init(val);
if(h->next==NULL){
h->next = temp;
}
else if(val<=(h->next->data)){
struct list_node *first = h->next;
temp->next=first;
h->next=temp;}
else{
struct list_node * pre;
struct list_node * post;
pre = h->next;
post = pre->next;
while(post!=NULL){
int t1 = pre->data;
int t2 = post->data;
if(t1<=val && val<t2){
temp->next=post;
pre->next=temp;
return;
}
pre=post;
post=pre->next;
}
pre->next=temp;
}
return;
}
void sortedStackPop(SortedStack* obj) {
if(sortedStackIsEmpty(obj))
return;
struct list_node * h = obj->head;
struct list_node *temp = h->next;
h->next=temp->next;
free(temp);
}
int sortedStackPeek(SortedStack* obj) {
if(sortedStackIsEmpty(obj))
return -1;
struct list_node * h = obj->head;
int ret = h->next->data;
return ret;
}
bool sortedStackIsEmpty(SortedStack* obj) {
if(obj->head->next==NULL)
return true;
else
return false;
}
void sortedStackFree(SortedStack* obj) {
struct list_node * h = obj->head;
while(h->next!=NULL){
struct list_node * temp = h->next;
h->next=temp->next;
free(temp);
}
free(h);
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);
*/