设计并实现堆栈和队列的各种操作算法,利用C语言
时间: 2024-10-09 11:00:56 浏览: 27
深入浅析C语言中堆栈和队列
在C语言中,设计和实现堆栈(Stack)和队列(Queue)可以分别使用数组或链表这两种数据结构。这里我会给出基本的操作算法:
**堆栈(Stack)实现:**
堆栈通常使用数组或链表头结点作为底端(LIFO原则,即最后入栈的元素最先出栈)。以下是部分操作算法:
1. **初始化堆栈:**
```c
typedef struct StackNode {
int data;
struct StackNode* next;
} Stack;
Stack* createStack() {
Stack* stack = (Stack*)malloc(sizeof(Stack));
stack->next = NULL;
return stack;
}
```
2. **压栈(Push):**
```c
void push(Stack* stack, int value) {
Stack* newNode = (Stack*)malloc(sizeof(Stack));
newNode->data = value;
newNode->next = stack->next;
stack->next = newNode;
}
```
3. **弹栈(Pop):**
```c
int pop(Stack* stack) {
if (stack->next == NULL)
return -1; // 栈空
int topValue = stack->next->data;
Stack* temp = stack->next;
stack->next = stack->next->next;
free(temp);
return topValue;
}
```
4. **查看栈顶元素(Peek):**
```c
int peek(Stack* stack) {
if (stack-1;
return stack->next->data;
}
```
**队列(Queue)实现:**
队列通常使用数组或双端队列(Deque,如`std::deque`)作为底层存储。以下是部分操作算法:
1. **初始化队列:**
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct QueueNode {
int data;
struct QueueNode* next;
struct QueueNode* prev;
} Queue;
Queue* createQueue() {
Queue* queue = (Queue*)malloc(sizeof(Queue));
queue->next = queue->prev = NULL;
return queue;
}
```
2. **入队(Enqueue):**
```c
void enqueue(Queue* queue, int value) {
Queue* newNode = (Queue*)malloc(sizeof(Queue));
newNode->data = value;
newNode->next = queue->next;
newNode->prev = queue;
if (queue->next != NULL)
queue->next->prev = newNode;
queue->next = newNode;
}
```
3. **出队(Dequeue):**
```c
int dequeue(Queue* queue) {
if (queue->next == NULL)
return -1; // 队列空
int frontValue = queue->next->data;
Queue* temp = queue->next;
queue->next = temp->next;
if (queue->next != NULL)
queue->next->prev = queue;
free(temp);
return frontValue;
}
```
4. **查看队首元素(Front):**
```c
int front(Queue* queue) {
if (queue->next == NULL)
return -1;
return queue->next->data;
}
```
阅读全文