栈的基本操作就是出栈和入栈,这两个的时间复杂度都是O(1)

数据结构

typedef struct Stack{
    int data[MAXSIZE];
    int top;
}Stack;

出栈操作

int Pop(Stack *s){
    if(s->top == -1)
        return 0;
    s->top--;
    return s->data[s->top+1];
}

入栈操作

int Push(Stack *s,int num){
    if(s->top == MAXSIZE-1)
        return 0;
    s->top++;
    s->data[s->top] = num;
    return 1;
}

实例代码

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #define MAXSIZE 20
 4 
 5 typedef struct Stack{
 6     int data[MAXSIZE];
 7     int top;
 8 }Stack;
 9 
10 void createStack(Stack *s,int n);
11 void showStack(Stack *s);
12 int Push(Stack *s,int num);
13 int Pop(Stack *s);
14 
15 int main()
16 {
17     Stack *s = (Stack *)malloc(sizeof(Stack));
18     createStack(s,5);
19     showStack(s);
20 
21     if(Push(s,0))
22         showStack(s);
23 
24     printf("the pop number is:%d\n",Pop(s));
25     printf("the pop number is:%d\n",Pop(s));
26     printf("the pop number is:%d\n",Pop(s));
27 
28     showStack(s);
29 
30     free(s);
31     return 0;
32 }
33 
34 void createStack(Stack *s,int n){
35     int i;
36     s->top=0;
37     for(i=0;i<n;i++){
38         s->data[i] = i*2+1;
39         s->top++;
40     }
41     s->top--;
42 }
43 
44 void showStack(Stack *s){
45     int i;
46     for(i=0;i<s->top+1;i++){
47         printf("%d->",s->data[i]);
48     }
49     printf("top\n");
50 }
51 
52 int Push(Stack *s,int num){
53     if(s->top == MAXSIZE-1)
54         return 0;
55     s->top++;
56     s->data[s->top] = num;
57     return 1;
58 }
59 int Pop(Stack *s){
60     if(s->top == -1)
61         return 0;
62     s->top--;
63     return s->data[s->top+1];
64 }

运行结果

posted @ 2014-01-27 11:05 xingoo 阅读(...) 评论(...) 编辑 收藏