第10章,基本数据结构(栈,队列)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
 
typedef struct _stack{
    int* arr;
    int top, size;
}stack;
stack createStack(int size)
{
    stack st;
    st.arr = (int*)malloc(size*sizeof(int));
    st.top = -1;
    st.size = size;
    return st;
}
int isEmptyStack(stack &s)
{
    return s.top == -1;
}
void push(stack &s, int val)
{
    if (s.top == s.size - 1){
        int *tmp = s.arr;
        s.arr = (int*)malloc(2 * s.size*sizeof(int));
        memcpy(s.arr, tmp, s.size*sizeof(int));
        s.size = s.size * 2;
    }
    ++s.top;
    s.arr[s.top] = val;
}
int pop(stack &s)
{
    if (isEmptyStack(s)){
        printf("stack is empty\n");
        exit(-1);
    }
    --s.top;
    return s.arr[s.top + 1];
}
 
 
typedef struct _queue{
    int *arr;
    int tail, head, size;
}queue;
queue createQueue(int size)
{
    queue q;
    q.tail = q.head = 0;
    q.arr = (int*)malloc(size*sizeof(int));
    q.size = size;
    return q;
}
void enqueue(queue &q, int val)
{
    if (q.head == (q.tail + 1) % q.size){
        int *tmp = q.arr;
        q.arr = (int*)malloc(2 * q.size*sizeof(int));
        memcpy(q.arr, tmp, q.size*sizeof(int));
        q.size = 2 * q.size;
    }
    q.arr[q.tail] = val;
    q.tail = (q.tail + 1) % q.size;
}
int dequeue(queue &q)
{
    if (q.tail == q.head){
        printf("queue is empty\n");
        exit(-1);
    }
    int res = q.arr[q.head];
    q.head = (q.head + 1) % q.size;
    return res;
}
 
int main()
{
    int a[] = { 1, 2, 3, 4, 5, 6, 7 };
    stack ss = createStack(5);
    for (int i = 0; i < 7; ++i)
        push(ss, a[i]);
    printf("%d\n", ss.size);
    for (int i = 0; i < 7; ++i)
        printf("%d\t", pop(ss));
    printf("\n");
 
    queue q = createQueue(5);
    for (int i = 0; i < 5; ++i)
        enqueue(q, a[i]);
    dequeue(q); dequeue(q);
    enqueue(q, 100); enqueue(q,200);
    for (int i = 0; i <6; ++i)
        printf("%d\t", dequeue(q));
}

  

posted @   湛雷冲  阅读(96)  评论(0编辑  收藏  举报
编辑推荐:
· 智能桌面机器人:用.NET IoT库控制舵机并多方法播放表情
· Linux glibc自带哈希表的用例及性能测试
· 深入理解 Mybatis 分库分表执行原理
· 如何打造一个高并发系统?
· .NET Core GC压缩(compact_phase)底层原理浅谈
阅读排行:
· 手把手教你在本地部署DeepSeek R1,搭建web-ui ,建议收藏!
· 新年开篇:在本地部署DeepSeek大模型实现联网增强的AI应用
· Janus Pro:DeepSeek 开源革新,多模态 AI 的未来
· 互联网不景气了那就玩玩嵌入式吧,用纯.NET开发并制作一个智能桌面机器人(三):用.NET IoT库
· 【非技术】说说2024年我都干了些啥
点击右上角即可分享
微信分享提示