剑指offer 面试题21 包含min函数的栈
来源:互联网 发布:刷空间人气软件 编辑:程序博客网 时间:2024/05/17 06:51
思路:
建立一个辅助栈,每次push的时候同时push当前的最小值到辅助栈。
#include <stdio.h>#include <stdlib.h>#define STACKSIZE 1024typedef struct Stack{int data[STACKSIZE];int vice[STACKSIZE];int topIndex;}MinStack;MinStack* init(MinStack *s);int min(MinStack *s);int top(MinStack *s);int pop(MinStack *s);MinStack* push(MinStack *s, int data);int main(int argc, char *argv[]){int arr[] = {3,1,5,4,2,8,0,7,9};MinStack *s = NULL;int i, t, m;for(i = 0 ; i<sizeof(arr)/sizeof(int) ; i++){s = push(s, arr[i]);}for(i = 0 ; i<sizeof(arr)/sizeof(int) ; i++){m = min(s);t = pop(s);printf("m = %d\t t = %d\n", m, t);} printf("\n");return 0;}int min(MinStack *s){if((s == NULL)||(s->topIndex == -1)){printf("MinStack is NULL");return 0;}return s->vice[s->topIndex];}MinStack* init(MinStack *s){if(s == NULL){s = (MinStack*)(malloc(sizeof(MinStack)));}s->topIndex = -1;return s;}int top(MinStack *s){if((s == NULL)||(s->topIndex == -1)){printf("MinStack is NULL");return 0;}return s->data[s->topIndex];}int pop(MinStack *s){if((s == NULL)||(s->topIndex == -1)){printf("MinStack is NULL");return 0;}int d = s->data[s->topIndex];s->topIndex--;//s->topIndex = s->topIndex-1; return d;}MinStack* push(MinStack *s, int data){if(s == NULL){s = init(s); }if(s->topIndex >= STACKSIZE){ //检查 printf("out of range!\n"); return s;}s->topIndex = s->topIndex+1;s->data[s->topIndex] = data;if(s->topIndex == 0){ //注意首个元素插入时候的特殊情况 s->vice[s->topIndex] = data;return s;}if(data < s->vice[s->topIndex-1]){s->vice[s->topIndex] = data;}else{s->vice[s->topIndex] = s->vice[s->topIndex-1] ;}return s;}
0 0
- [剑指offer][面试题21]包含min函数的栈
- 剑指offer 面试题21:包含min函数的栈
- 【剑指offer】面试题21:包含min函数的栈
- 【剑指offer】面试题21:包含min函数的栈
- 剑指Offer:面试题21 包含min函数的栈
- 剑指offer 面试题21 包含min函数的栈
- 《剑指Offer》面试题21:包含min函数的栈
- 剑指offer面试题21-包含min函数的栈
- 剑指offer-面试题21:包含min函数的栈
- 剑指Offer----面试题21:包含min函数的栈
- 剑指offer-面试题21:包含min函数的栈
- 剑指offer面试题21:包含min函数的栈
- 剑指Offer面试题21:包含min函数的栈
- 剑指offer--面试题21:包含min函数的栈
- 剑指Offer---面试题21:包含min函数的栈
- 剑指offer-面试题21-包含min函数的栈
- 【剑指offer】面试题21:包含min函数的栈
- 【面试题】剑指Offer-21-包含Min函数的栈
- 在ubuntu安装R
- Linux学习_arch软件安装与配置
- 搭建centos7的server环境
- 怎么上facebook、youtube、twitter? 图文教程。
- Java垃圾回收机制
- 剑指offer 面试题21 包含min函数的栈
- iOS学习笔记基础-oc06内存管理
- 2015年校招--华为上机笔试题--大数相乘
- 配置solr4.10.0和中文分词IKAnalyzer
- JAVA、PHP、RUBY、PYTHON、HTML等语言视频教程合集,很全面,值得收藏。
- linux文件和目录操作
- JAVA中String与StringBuffer的区别
- bo2-About Java 多线程 -------->Java多线程程序设计(unLook!)
- java反射机制剖析(三)—类类型Class