初学数据结构——栈和队列

    昨天去理发,蘑菇头!!!!。好伤心,我多年留的长发,就这样没了,而且还被剪得这么糟糕。以后再也不随便到学校外面的理发店理发了。

  (本来就因为天气热,想想自己一直都是长发,没换过风格,都上大学了,决定还是换换风格,结果越看越心碎。>_<);

    理发回来后就直接看书了,发现栈和队列真的一正一反。但是我没按照书上用指针和结构体实现,只是用数组实现了部分功能,但是我感觉这些功能够用了。

    要写其他功能也不难。我觉得数组操作起来比较简单,唯一的缺点就是,浪费空间。书上说的,是动态数组。主要是自己懒,而且理了这么个头发。心碎了。

 1 #include <iostream>
 2 #include <stdio.h>
 3 #include <stack>
 4 #include <string.h>
 5 using namespace std;
 6 
 7 #define MAXN 1000000
 8 
 9 int qstack[MAXN];
10 int top;
11 
12 void init_stack()
13 {
14     top = 0;
15     memset(qstack,0,sizeof(qstack));
16 }
17 
18 int stack_empty()
19 {
20     if(top == 0)
21         return 1;
22     return 0;
23 }
24 
25 void stack_push(int value)
26 {
27     if(top == MAXN)
28         printf("Stack Full\n");
29     else
30         qstack[++top]=value;
31 }
32 
33 void stack_pop()
34 {
35     if(!stack_empty())
36         qstack[--top];
37     else
38         printf("No elem\n");
39 }
40 
41 int stack_top()
42 {
43     if(!stack_empty())
44         return qstack[top];
45     else
46         return -1;
47 }
48 
49 int main()
50 {
51     init_stack();
52     stack_push(5);
53     stack_push(4);
54     stack_push(3);
55     stack_push(2);
56     stack_push(1);
57     while(!stack_empty())
58     {
59         printf("%d\n",stack_top());
60         stack_pop();
61     }
62     printf("------------STL Stack-----------\n");
63     stack<int> s;
64     s.push(5);
65     s.push(4);
66     s.push(3);
67     s.push(2);
68     s.push(1);
69     while(!s.empty())
70     {
71         printf("%d\n",s.top());
72         s.pop();
73     }
74     return 0;
75 }

队列

 1 #include <stdio.h>
 2 #include <string.h>
 3 #include <queue>
 4 #include <iostream>
 5 
 6 using namespace std;
 7 
 8 #define MAXN 100000
 9 
10 int squeue[MAXN];
11 int fron = 0;
12 int rear = 0;
13 
14 void queue_init()
15 {
16     memset(squeue,0,sizeof(squeue));
17     fron = 0;
18     rear = 0;
19 }
20 
21 int queue_empty()
22 {
23     if(rear == fron)
24         return 1;
25     else
26         return 0;
27 }
28 
29 void queue_push(int value)
30 {
31     squeue[rear++] = value;
32 }
33 
34 void queue_pop()
35 {
36     if(!queue_empty())
37         squeue[++fron];
38     else
39         printf("Queue is empty");
40 }
41 
42 int queue_front()
43 {
44    if(!queue_empty())
45         return squeue[fron];
46    else
47         return 0;
48 }
49 
50 int main()
51 {
52     queue_init();
53     queue_push(5);
54     queue_push(4);
55     queue_push(3);
56     queue_push(2);
57     queue_push(1);
58     while(!queue_empty())
59     {
60         printf("%d\n",queue_front());
61         queue_pop();
62     }
63     printf("------------STL Queue-----------\n");
64     queue<int> q;
65     q.push(5);
66     q.push(4);
67     q.push(3);
68     q.push(2);
69     q.push(1);
70     while(!q.empty())
71     {
72         printf("%d\n",q.front());
73         q.pop();
74     }
75     return 0;
76 }

 

posted @ 2013-08-12 09:33  清瞳浅水  阅读(300)  评论(0编辑  收藏  举报