• 数据结构初步(九)- 栈和队列oj练习


    1.jpg

    前言

    栈和队列加强计划!


    1. 有效的括号

    1.1题目链接

    力扣(leetcode):有效的括号


    1.2 题目要求

    给定一个只包括 **‘(’,‘)’,‘{’,‘}’,‘[’,‘]’ **的字符串 s s s ,判断字符串是否有效。
    有效字符串需满足:
    左括号必须用相同类型的右括号闭合。
    左括号必须以正确的顺序闭合。
    每个右括号都有一个对应的相同类型的左括号。
    示例 1:
    输入: s s s = “()”
    输出: t r u e true true
    示例 2:
    输入: s s s = “()[]{}”
    输出: t r u e true true
    示例 3:
    输入: s s s = “(]”
    输出: f a l s e false false
    提示:
    1 < = s . l e n g t h < = 104 1 <= s.length <= 104 1<=s.length<=104
    s s s 仅由括号 ‘()[]{}’ 组成


    1.3 C代码框架

    bool isValid(char * s){
    
    }
    
    • 1
    • 2
    • 3

    1.4 思路分析

    ( 1 ) (1) (1)括号匹配问题,选择数据结构栈进行解决,栈的性质是后进先出的。
    ( 2 ) (2) (2)判断字符串中哪两个括号是否匹配既不能比较字符串中前后的括号,也不能从字符串对称位置依次比较。这两种方式都不能完全覆盖所有括号匹配情况。
    ( 3 ) (3) (3)栈中遇到左括号就保存,遇到字符串的右括号就取出栈中的左括号进行匹配判断,如果匹配就继续;如果存在栈中取出的左括号与字符串中右括号不匹配,就释放栈并返回false
    ( 4 ) (4) (4)一些注意:
    在遇到右括号之后进行匹配判断时取出栈中数据之前,需要先判断栈是否为空,空栈不能取数据。
    如果字符串匹配之后只剩下一个左括号,需要特殊处理一下:判断栈是否为空,括号匹配之后栈里应该为空,如果不为空就说明括号不匹配。

    时间复杂度 O ( n ) O(n) O(n)
    空间复杂度 O ( n ) O(n) O(n)

    在这里插入图片描述


    1.5 代码实现

    typedef char STDataType;
    typedef struct Stack {
    	STDataType* data;
    	int pop;
    	int capacity;
    }ST;
    
    //初始化
    void StackInit(ST* pst);
    
    //销毁栈
    void StackDestroy(ST* pst);
    
    //入栈
    void StackPush(ST* pst, STDataType val);
    
    //出栈
    void StackPop(ST* pst);
    
    //取出栈顶元素
    STDataType StackTop(ST* pst);
    
    //判断栈是否是空
    bool StackEmpty(ST* pst);
    
    //返回栈的大小
    int StackSize(ST* pst);
    
    //初始化
    void StackInit(ST* pst) {
    	assert(pst);
    	pst->data = NULL;
    	pst->pop = pst->capacity = 0;
    }
    
    //销毁栈
    void StackDestroy(ST* pst) {
    	assert(pst);
    	free(pst->data);
    	pst->pop = pst->capacity = 0;
    }
    
    //入栈
    void StackPush(ST* pst, STDataType val) {
    	assert(pst);
    	//扩容
    	if (pst->pop == pst->capacity) {
    		int newCapacity = pst->capacity == 0 ? 4 : pst->capacity * 2;
    		STDataType* tmp = (STDataType*)realloc(pst->data, sizeof(STDataType) * newCapacity);
    		if (!tmp) {
    			perror("StackPush");
    		}
    		pst->data = tmp;
    		pst->capacity = newCapacity;
    	}
    	pst->data[pst->pop] = val;
    	++pst->pop;
    }
    
    //出栈
    void StackPop(ST* pst) {
    	assert(pst);
    	assert(!StackEmpty(pst));
    	--pst->pop;
    }
    
    //取出栈顶元素
    STDataType StackTop(ST* pst) {
    	assert(pst);
    	return pst->data[pst->pop-1];
    }
    
    //判断栈是否是空
    bool StackEmpty(ST* pst) {
    	assert(pst);
    	return pst->pop == 0;
    }
    
    //返回栈的大小
    int StackSize(ST* pst) {
    	assert(pst);
    	return pst->pop;
    }
    
    
    bool isValid(char * s){
        ST obj;
        StackInit(&obj);
        while(*s){
            //左括号就入栈
            if(*s == '(' || *s == '[' || *s == '{'){
                StackPush(&obj, *s);
            }
            else{
            //左右括号时匹配就继续循环,不匹配就返回false
                //右括号时需要取栈里元素进行比较,栈里却为空
                if(StackEmpty(&obj)){
                    StackDestroy(&obj);
                    return false;
                }
                if((*s == ')' && StackTop(&obj) !='(')
                ||(*s == ']' && StackTop(&obj) !='[')
                ||(*s == '}' && StackTop(&obj) !='{')){
                    StackDestroy(&obj);
                    return false;
                }
                else{
                    StackPop(&obj);
                }
            }
            ++s;
        }
        //左右括号完全匹配后栈最后应该为空,如果不为空就是左右括号不匹配
        int flag = StackEmpty(&obj);
        return flag;
    }
    
    • 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
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116

    2. 用队列实现栈

    2.1题目链接

    力扣(leetcode):用队列实现栈


    2.2 题目要求

    请你仅使用两个队列实现一个后入先出( L I F O LIFO LIFO)的栈,并支持普通栈的全部四种操作( p u s h 、 t o p 、 p o p 和 e m p t y push、top、pop 和 empty pushtoppopempty)。
    实现 MyStack 类:
    void push(int x) 将元素 x 压入栈顶。
    int pop() 移除并返回栈顶元素。
    int top() 返回栈顶元素。
    boolean empty() 如果栈是空的,返回 true ;否则,返回 false
    注意:
    你只能使用队列的基本操作 —— 也就是 push to back、peek/pop from front、size 和 is empty 这些操作。
    你所使用的语言也许不支持队列。 你可以使用 list (列表)或者 deque(双端队列)来模拟一个队列 , 只要是标准的队列操作即可。
    示例:
    输入:
    [“MyStack”, “push”, “push”, “top”, “pop”, “empty”]
    [ [ ], [1], [2], [ ], [ ], [ ] ]
    输出:
    [null, null, null, 2, 2, false]

    解释:
    MyStack myStack = new MyStack();
    myStack.push(1);
    myStack.push(2);
    myStack.top(); // 返回 2
    myStack.pop(); // 返回 2
    myStack.empty(); // 返回 False

    提示:
    1 <= x <= 9
    最多调用100 次 push、pop、top 和 empty
    每次调用 pop 和 top 都保证栈不为空

    进阶:你能否仅用一个队列来实现栈。


    2.3 C代码框架

    typedef struct {
    
    } MyStack;
    
    
    MyStack* myStackCreate() {
    
    }
    
    void myStackPush(MyStack* obj, int x) {
    
    }
    
    int myStackPop(MyStack* obj) {
    
    }
    
    int myStackTop(MyStack* obj) {
    
    }
    
    bool myStackEmpty(MyStack* obj) {
    
    }
    
    void myStackFree(MyStack* obj) {
    
    }
    
    /**
     * Your MyStack struct will be instantiated and called as such:
     * MyStack* obj = myStackCreate();
     * myStackPush(obj, x);
     
     * int param_2 = myStackPop(obj);
     
     * int param_3 = myStackTop(obj);
     
     * bool param_4 = myStackEmpty(obj);
     
     * myStackFree(obj);
    */
    
    • 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

    2.4 思路分析

    ( 1 ) (1) (1)的性质是后进先出队列的性质是先进后出。二者性质恰好相反。
    ( 2 ) (2) (2)对于入数据来说,栈是在栈顶入数据,队列是在队尾入数据;对于出数据来说,栈是在栈顶出数据,队列是在队头出数据。
    ( 3 ) (3) (3)入数据时入在栈顶,对应于入在队尾。初始两个空队列,入数据时只入其中一个空队列,时刻保持着一个队列是空,另一个队列不是空的状态。
    ( 4 ) (4) (4)栈从栈顶出一个数据(出栈),对应于队列需要出队尾的数据,但是队列又只能出队头的数据,所以需要把队尾数据之前的数据先入数据到另一个空队列,然后再出剩余的队尾数据。在此过程中一直保持者一个队列为空,一个队列不为空,空队列准备接受非空队列的数据导入,然后空和非空状态交换。
    在这里插入图片描述


    2.5 代码实现

    //链表形式的队列实现
    //封装为节点
    typedef int QDataType;
    typedef struct QueueNode {
    	QDataType val;
    	struct QueueNode* next;
    }QNode;
    
    //封装节点指针为
    typedef struct Queue {
    	QNode* head;
    	QNode* tail;
    	int size;
    }Queue;
    
    //初始化
    void QueueInit(Queue* pq);
    
    //销毁队列
    void QueueDestroy(Queue* pq);
    
    //入队列
    void QueuePush(Queue* pq, QDataType val);
    
    //出队列
    void QueuePop(Queue* pq);
    
    //取队头数据
    QDataType QueueHead(Queue* pq);
    
    //取队尾数据
    QDataType QueueTail(Queue* pq);
    
    //判断队列是否为空
    bool QueueEmpty(Queue* pq);
    
    //计算队列长度
    int QueueSize(Queue* pq);
    
    
    //初始化
    void QueueInit(Queue* pq) {
    	assert(pq);
    	pq->head = pq->tail = NULL;
    	pq->size = 0;
    }
    
    //销毁队列
    void QueueDestroy(Queue* pq) {
    	assert(pq);
    	QNode* cur = pq->head;
    	while (cur) {
    		QNode* del = cur;
    		cur = cur->next;
    		free(del);
    	}
    	/*while (cur) {
    		QNode* later = cur->next;
    		free(cur);
    		cur = later;
    	}*/
    }
    
    //入队列
    void QueuePush(Queue* pq, QDataType val) {
    	assert(pq);
    	//申请新节点,申请失败就退出程序
    	QNode* newnode = (QNode*)malloc(sizeof(QNode));
    	if (!newnode) {
    		perror("QueuePush");
    		exit(-1);
    	}
    	newnode->val = val;
    	newnode->next = NULL;
    	//链表尾插分为两种情况:
    	//1.队头指针为空
    	if (pq->head == NULL) {
    		pq->head = pq->tail = newnode;
    	}
    	//2.队头指针不为空
    	else {
    		//先链接前后节点,在更新尾节点
    		pq->tail->next = newnode;
    		pq->tail = newnode;
    	}
    	++pq->size;
    }
    
    //出队列
    void QueuePop(Queue* pq) {
    	assert(pq);
    	assert(!QueueEmpty(pq));
    	//防止tail野指针
    	if (pq->head == pq->tail) {
    		free(pq->head);
    		pq->head = pq->tail = NULL;
    	}
    	else {
    		QNode* del = pq->head;
    		pq->head = pq->head->next;
    		free(del);
    		del = NULL;
    	}
    	--pq->size;
    }
    
    //取队头数据
    QDataType QueueHead(Queue* pq) {
    	assert(pq);
    	return pq->head->val;
    }
    
    //取队尾数据
    QDataType QueueTail(Queue* pq) {
    	assert(pq);
    	return pq->tail->val;
    }
    
    //判断队列是否为空
    bool QueueEmpty(Queue* pq) {
    	assert(pq);
    	return pq->head == NULL && pq->tail == NULL;
    }
    
    //计算队列长度
    int QueueSize(Queue* pq) {
    	assert(pq);
    	//遍历法,效率较低
    	/*int n = 0;
    	QNode* cur = pq->head;
    	while (cur) {
    		++n;
    		cur = cur->next;
    	}
    	return n;*/
    
    	/*直接在队列结构体里定义一个size,每次入队列或出队列同时改变size,
    	使用时直接从结构体内返回即可*/
    	return pq->size;
    }
    
    //两个队列模拟栈
    typedef struct {
        Queue q1;
        Queue q2;
    } MyStack;
    
    
    MyStack* myStackCreate() {
        MyStack* obj = (MyStack*)malloc(sizeof(MyStack));
        QueueInit(&obj->q1);
        QueueInit(&obj->q2);
        return obj;
    }
    
    void myStackPush(MyStack* obj, int x) {
        //两个队列,初始都为空,有数据时则只有一个队列有数据
        if(!QueueEmpty(&obj->q1)){
            QueuePush(&obj->q1, x);
        }
        else{
            QueuePush(&obj->q2, x);
        }
    }
    
    int myStackPop(MyStack* obj) {
        //不知道哪个队列有数据,仍是假设法
        Queue* Empty = &obj->q1;
        Queue* NonEmpty = & obj->q2;
        if(!QueueEmpty(&obj->q1)){
            NonEmpty = &obj->q1;
            Empty = &obj->q2;
        }
    
        //有数据队列循环倒入无数据队列,至有数据队列只剩一个元素,该数据就是所删数据
        while(QueueSize(NonEmpty) > 1){
            QueuePush(Empty, QueueHead(NonEmpty));
            QueuePop(NonEmpty);
        }
        int tmp = QueueHead(NonEmpty);
        QueuePop(NonEmpty);
        return tmp;
    }
    
    int myStackTop(MyStack* obj) {
        //不知道哪个队列有数据,仍是假设法
        Queue* Empty = &obj->q1;
        Queue* NonEmpty = & obj->q2;
        if(!QueueEmpty(&obj->q1)){
            NonEmpty = &obj->q1;
            Empty = &obj->q2;
        }
        return QueueTail(NonEmpty);
    }
    
    bool myStackEmpty(MyStack* obj) {
        return QueueEmpty(&obj->q1) && QueueEmpty(&obj->q2);
    }
    
    void myStackFree(MyStack* obj) {
        QueueDestroy(&obj->q1);
        QueueDestroy(&obj->q2);
        free(obj);
    }
    
    /**
     * Your MyStack struct will be instantiated and called as such:
     * MyStack* obj = myStackCreate();
     * myStackPush(obj, x);
     
     * int param_2 = myStackPop(obj);
     
     * int param_3 = myStackTop(obj);
     
     * bool param_4 = myStackEmpty(obj);
     
     * myStackFree(obj);
    */
    
    • 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
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164
    • 165
    • 166
    • 167
    • 168
    • 169
    • 170
    • 171
    • 172
    • 173
    • 174
    • 175
    • 176
    • 177
    • 178
    • 179
    • 180
    • 181
    • 182
    • 183
    • 184
    • 185
    • 186
    • 187
    • 188
    • 189
    • 190
    • 191
    • 192
    • 193
    • 194
    • 195
    • 196
    • 197
    • 198
    • 199
    • 200
    • 201
    • 202
    • 203
    • 204
    • 205
    • 206
    • 207
    • 208
    • 209
    • 210
    • 211
    • 212
    • 213
    • 214
    • 215
    • 216
    • 217
    • 218

    3. 用栈实现队列

    1.1题目链接

    力扣(leetcode):用栈实现队列


    1.2 题目要求

    请你仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作(push、pop、peek、empty):
    实现 MyQueue 类:
    void push(int x) 将元素 x 推到队列的末尾
    int pop() 从队列的开头移除并返回元素
    int peek() 返回队列开头的元素
    boolean empty() 如果队列为空,返回 true ;否则,返回 false
    说明:
    你 只能 使用标准的栈操作 —— 也就是只有 push to top, peek/pop from top, size, 和 is empty 操作是合法的。
    你所使用的语言也许不支持栈。你可以使用 list 或者 deque(双端队列)来模拟一个栈,只要是标准的栈操作即可。
    示例 1:
    输入:
    [“MyQueue”, “push”, “push”, “peek”, “pop”, “empty”]
    [[], [1], [2], [], [], []]
    输出:
    [null, null, null, 1, 1, false]

    解释:
    MyQueue myQueue = new MyQueue();
    myQueue.push(1); // queue is: [1]
    myQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue)
    myQueue.peek(); // return 1
    myQueue.pop(); // return 1, queue is [2]
    myQueue.empty(); // return false

    提示:
    1 <= x <= 9
    最多调用 100 次 push、pop、peek 和 empty
    假设所有操作都是有效的 (例如,一个空的队列不会调用 pop 或者 peek 操作)

    进阶:
    你能否实现每个操作均摊时间复杂度为 O(1) 的队列?换句话说,执行 n 个操作的总时间复杂度为 O(n) ,即使其中一个操作可能花费较长时间。


    1.3 C代码框架

    typedef struct {
    
    } MyQueue;
    
    
    MyQueue* myQueueCreate() {
    
    }
    
    void myQueuePush(MyQueue* obj, int x) {
    
    }
    
    int myQueuePop(MyQueue* obj) {
    
    }
    
    int myQueuePeek(MyQueue* obj) {
    
    }
    
    bool myQueueEmpty(MyQueue* obj) {
    
    }
    
    void myQueueFree(MyQueue* obj) {
    
    }
    
    /**
     * Your MyQueue struct will be instantiated and called as such:
     * MyQueue* obj = myQueueCreate();
     * myQueuePush(obj, x);
     
     * int param_2 = myQueuePop(obj);
     
     * int param_3 = myQueuePeek(obj);
     
     * bool param_4 = myQueueEmpty(obj);
     
     * myQueueFree(obj);
    */
    
    • 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

    1.4 思路分析

    ( 1 ) (1) (1)的性质是后进先出队列的性质是先进后出。二者性质恰好相反。
    ( 2 ) (2) (2)对于入数据来说,栈是在栈顶入数据,队列是在队尾入数据;对于出数据来说,栈是在栈顶出数据,队列是在队头出数据。
    ( 3 ) (3) (3)队列入数据时入在队尾,对应于栈入数据在栈顶。
    ( 4 ) (4) (4)队列从队头出数据,而栈只能从栈顶出数据。这样想出的数据就在栈底,把栈中的数据依次在栈顶出,并导入另一个栈里,那么原来的数据顺序就反了过来,想出的数据就在另一个栈的栈顶了然后出反过来的数据的栈顶。
    ( 5 ) (5) (5)然后我们可以选择再把数据导入原来的栈,并等待之后的可能的操作,这样数据将在两个栈里相互倒来倒去,时间效率就不高了。
    所以我们直接把一个栈作为只入数据的栈PushStack另一个栈作为只出数据的栈PopStack
    当栈PopStack为空时,就把栈PushStack中所有数据依次出栈并入栈到PopStack ,为接下来可能的操作做准备。这样就不需要数据多次的倒来倒去,而是只需要倒一次,时间效率就高了。
    在这里插入图片描述


    1.5 代码实现

    //顺序表实现栈
    typedef int STDataType;
    typedef struct Stack {
    	STDataType* data;
    	int top;
    	int capacity;
    }ST;
    
    //初始化
    void StackInit(ST* pst);
    
    //销毁栈
    void StackDestroy(ST* pst);
    
    //入栈
    void StackPush(ST* pst, STDataType val);
    
    //出栈
    void StackPop(ST* pst);
    
    //取出栈顶元素
    STDataType StackTop(ST* pst);
    
    //判断栈是否是空
    bool StackEmpty(ST* pst);
    
    //返回栈的大小
    int StackSize(ST* pst);
    
    //初始化
    void StackInit(ST* pst) {
    	assert(pst);
    	pst->data = NULL;
    	pst->top = pst->capacity = 0;
    }
    
    //销毁栈
    void StackDestroy(ST* pst) {
    	assert(pst);
    	free(pst->data);
    	pst->top = pst->capacity = 0;
    }
    
    //入栈
    void StackPush(ST* pst, STDataType val) {
    	assert(pst);
    	//扩容
    	if (pst->top == pst->capacity) {
    		int newCapacity = pst->capacity == 0 ? 4 : pst->capacity * 2;
    		STDataType* tmp = (STDataType*)realloc(pst->data, sizeof(STDataType) * newCapacity);
    		if (!tmp) {
    			perror("StackPush");
    		}
    		pst->data = tmp;
    		pst->capacity = newCapacity;
    	}
    	pst->data[pst->top] = val;
    	++pst->top;
    }
    
    //出栈
    void StackPop(ST* pst) {
    	assert(pst);
    	assert(!StackEmpty(pst));
    	--pst->top;
    }
    
    //取出栈顶元素
    STDataType StackTop(ST* pst) {
    	assert(pst);
    	return pst->data[pst->top -1];
    }
    
    //判断栈是否是空
    bool StackEmpty(ST* pst) {
    	assert(pst);
    	return pst->top == 0;
    }
    
    //返回栈的大小
    int StackSize(ST* pst) {
    	assert(pst);
    	return pst->top;
    }
    
    //两个栈模拟队列
    typedef struct {
        ST StPush;
        ST StPop;
    } MyQueue;
    
    
    MyQueue* myQueueCreate() {
        MyQueue* obj = (MyQueue*)malloc(sizeof(MyQueue));
        StackInit(&obj->StPush);
        StackInit(&obj->StPop);
        return obj;
    }
    
    void myQueuePush(MyQueue* obj, int x) {
        StackPush(&obj->StPush, x);
    }
    
    int myQueuePop(MyQueue* obj) {
        //如果出数据的栈为空,就把入数据的栈数据全倒入出数据的栈
        if(StackEmpty(&obj->StPop)){
            while(!StackEmpty(&obj->StPush)){
                StackPush(&obj->StPop, StackTop(&obj->StPush));
                StackPop(&obj->StPush);
            }
        }
        int tmp = StackTop(&obj->StPop);
        StackPop(&obj->StPop);
        return tmp;
    }
    
    int myQueuePeek(MyQueue* obj) {
        //如果出数据的栈为空,就把入数据的栈数据全倒入出数据的栈
        if(StackEmpty(&obj->StPop)){
            while(StackSize(&obj->StPush)){
                StackPush(&obj->StPop, StackTop(&obj->StPush));
                StackPop(&obj->StPush);
            }
        }
        //出数据栈的栈顶元素就是队列开头的数据
        return StackTop(&obj->StPop);
    }
    
    bool myQueueEmpty(MyQueue* obj) {
        //两个栈都是空,队列才是空
        return StackEmpty(&obj->StPush) && StackEmpty(&obj->StPop);
    }
    
    void myQueueFree(MyQueue* obj) {
        //谁申请的空间谁释放,注意释放时的先后顺序
        StackDestroy(&obj->StPush);
        StackDestroy(&obj->StPop);
        free(obj);
    }
    
    /**
     * Your MyQueue struct will be instantiated and called as such:
     * MyQueue* obj = myQueueCreate();
     * myQueuePush(obj, x);
     
     * int param_2 = myQueuePop(obj);
     
     * int param_3 = myQueuePeek(obj);
     
     * bool param_4 = myQueueEmpty(obj);
     
     * myQueueFree(obj);
    */
    
    • 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
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153

    4. 设计循环队列

    1.1题目链接

    力扣(leetcode):设计循环队列


    1.2 题目要求

    设计你的循环队列实现。 循环队列是一种线性数据结构,其操作表现基于 FIFO(先进先出)原则并且队尾被连接在队首之后以形成一个循环。它也被称为“环形缓冲器”。
    循环队列的一个好处是我们可以利用这个队列之前用过的空间。在一个普通队列里,一旦一个队列满了,我们就不能插入下一个元素,即使在队列前面仍有空间。但是使用循环队列,我们能使用这些空间去存储新的值。
    你的实现应该支持如下操作:
    MyCircularQueue(k): 构造器,设置队列长度为 k 。
    Front: 从队首获取元素。如果队列为空,返回 -1 。
    Rear: 获取队尾元素。如果队列为空,返回 -1 。
    enQueue(value): 向循环队列插入一个元素。如果成功插入则返回真。
    deQueue(): 从循环队列中删除一个元素。如果成功删除则返回真。
    isEmpty(): 检查循环队列是否为空。
    isFull(): 检查循环队列是否已满。

    示例:
    MyCircularQueue circularQueue = new MyCircularQueue(3); // 设置长度为 3
    circularQueue.enQueue(1); // 返回 true
    circularQueue.enQueue(2); // 返回 true
    circularQueue.enQueue(3); // 返回 true
    circularQueue.enQueue(4); // 返回 false,队列已满
    circularQueue.Rear(); // 返回 3
    circularQueue.isFull(); // 返回 true
    circularQueue.deQueue(); // 返回 true
    circularQueue.enQueue(4); // 返回 true
    circularQueue.Rear(); // 返回 4
    提示:
    所有的值都在 0 至 1000 的范围内;
    操作数将在 1 至 1000 的范围内;
    请不要使用内置的队列库。


    1.3 C代码框架

    typedef struct {
    
    } MyCircularQueue;
    
    
    MyCircularQueue* myCircularQueueCreate(int k) {
    
    }
    
    bool myCircularQueueEnQueue(MyCircularQueue* obj, int value) {
    
    }
    
    bool myCircularQueueDeQueue(MyCircularQueue* obj) {
    
    }
    
    int myCircularQueueFront(MyCircularQueue* obj) {
    
    }
    
    int myCircularQueueRear(MyCircularQueue* obj) {
    
    }
    
    bool myCircularQueueIsEmpty(MyCircularQueue* obj) {
    
    }
    
    bool myCircularQueueIsFull(MyCircularQueue* obj) {
    
    }
    
    void myCircularQueueFree(MyCircularQueue* obj) {
    
    }
    
    /**
     * Your MyCircularQueue struct will be instantiated and called as such:
     * MyCircularQueue* obj = myCircularQueueCreate(k);
     * bool param_1 = myCircularQueueEnQueue(obj, value);
     
     * bool param_2 = myCircularQueueDeQueue(obj);
     
     * int param_3 = myCircularQueueFront(obj);
     
     * int param_4 = myCircularQueueRear(obj);
     
     * bool param_5 = myCircularQueueIsEmpty(obj);
     
     * bool param_6 = myCircularQueueIsFull(obj);
     
     * myCircularQueueFree(obj);
    */
    
    • 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

    1.4 思路分析

    ( 1 ) (1) (1)循环队列,实现就定义好了最多能同时存放的数据个数,逻辑上是头尾相连的。
    ( 2 ) (2) (2)循环队列也是队列的一种,可以用顺序表实现,也可以用链表实现。链表实现理解起来比较简单,尾节点内不指针成员指向头结点,但是实现起来细节较多,实现并不容易;顺序表实现其实也很好理解,实现也并不复杂,需要考虑的细节也没有那么多。
    ( 3 ) (3) (3)我们是用顺序表实现循环队列。一开始队头head和队尾tail都置为0,都指向数组下标为0的位置,这样初始化后尾下标指向的是尾元素的下一个位置。这样入数据时,我们无法区分循环队列空和满这两种不同的循环队列的状态,因为空和满时下标headtail都相同。
    ( 4 ) (4) (4)我们可以有几种解决方法:
    方法1:额外创建一个整型变量size辅助记录循环队列元素个数,这样通过size的大小就可以区分空和满了;
    方法2:假如循环队列计划最多同时储存K个元素,我们在开辟数组时不再是开辟K个空间,而是开辟K+1个空间,于是因为这多开的一个空间,循环队列中总是至少有一个位置是没有有效数据元素的。
    这样不需要再借助辅助变量size,直接就可以通过下标headtail的关系判断循环队列是空还是满了。(循环队列是空:head == tail、循环队列是满:head == (tail+1)%(k+1)

    在这里插入图片描述
    在这里插入图片描述
    在这里插入图片描述


    1.5 代码实现

    typedef int DataType;
    typedef struct {
        DataType* val;
        int head;
        int tail;
        int N;
    } MyCircularQueue;
    
    
    MyCircularQueue* myCircularQueueCreate(int k) {
        MyCircularQueue* obj = (MyCircularQueue*)malloc(sizeof(MyCircularQueue));
        obj->N = k + 1;
        obj->val = (DataType*)malloc(sizeof(DataType)*obj->N);
        obj->head = obj->tail = 0;
        return obj;
    }
    
    bool myCircularQueueEnQueue(MyCircularQueue* obj, int value) {
        //满了就不能继续入数据
        if(obj->head == (obj->tail+1)%obj->N){
            return false;
        }
        else{
            obj->val[obj->tail] = value;
            ++obj->tail;
            //防止下标越界
            obj->tail %= obj->N;
            return true;
        }
    }
    
    bool myCircularQueueDeQueue(MyCircularQueue* obj) {
        //空了就不能再出数据
        if(obj->head == obj->tail){
            return false;
        }
        else{
            ++obj->head;
            //防止下标越界
            obj->head %= obj->N;
            return true;
        }
    }
    
    int myCircularQueueFront(MyCircularQueue* obj) {
        //队列为空返回false
        if(obj->head == obj->tail){
            return -1;
        }
        else{
            return obj->val[obj->head];
        }
    }
    
    int myCircularQueueRear(MyCircularQueue* obj) {
        //队列为空返回false
        if(obj->head == obj->tail){
            return -1;
        }
        else{
            return obj->val[(obj->tail-1+obj->N)%obj->N];
        }
    }
    
    bool myCircularQueueIsEmpty(MyCircularQueue* obj) {
        return obj->head == obj->tail;
    }
    
    bool myCircularQueueIsFull(MyCircularQueue* obj) {
        //逻辑上tail的下一个位置是head循环队列就满了,
        //实际需要处理一下防止tail+1越界
        return obj->head == (obj->tail+1)%obj->N;
    }
    
    void myCircularQueueFree(MyCircularQueue* obj) {
        //动态开辟几次就释放几次
        free(obj->val);
        free(obj);
    }
    
    /**
     * Your MyCircularQueue struct will be instantiated and called as such:
     * MyCircularQueue* obj = myCircularQueueCreate(k);
     * bool param_1 = myCircularQueueEnQueue(obj, value);
     
     * bool param_2 = myCircularQueueDeQueue(obj);
     
     * int param_3 = myCircularQueueFront(obj);
     
     * int param_4 = myCircularQueueRear(obj);
     
     * bool param_5 = myCircularQueueIsEmpty(obj);
     
     * bool param_6 = myCircularQueueIsFull(obj);
     
     * myCircularQueueFree(obj);
    */
    
    • 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
    • 96
    • 97

    结语

    栈和队列的题就分享到这里,感谢看到这里的你!!!


    E N D END END

  • 相关阅读:
    mediaPlayer MediaPlayer 读取 字节数组
    SpringCloud微服务(五)——Config分布式配置中心
    后端文章合集
    web通信基础
    跨境人,是继续坚守还是求新变新?(Starday)
    【力扣1876】长度为三且各字符不同的子字符串
    Python实战项目:俄罗斯方块(源码分享)(文章较短,直接上代码)
    网络安全(黑客)—自学
    Nodejs+vue汽车保养美容管理系统vscode前后端分离项目
    机器学习笔记 - 时间序列的混合模型
  • 原文地址:https://blog.csdn.net/weixin_64904163/article/details/126845220