第四节、堆栈
1.数组形式堆栈的实现
(1)堆栈的定义以及结构体
堆栈可以理解为先入后出,一端进一端出。它的结构体为:
1 2 3 4 5 6 7
| #define MAX_SIZE 100
typedef struct { int data[MAX_SIZE]; int top; } Stack;
|
(2)队列的基本操作的实现
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
| #include <stdio.h> #include <stdlib.h>
#define MAX_SIZE 100
typedef struct { int data[MAX_SIZE]; int top; } Stack;
void initStack(Stack* stack) { stack->top = -1; }
int isEmpty(Stack* stack) { return stack->top == -1; }
int isFull(Stack* stack) { return stack->top == MAX_SIZE - 1; }
int push(Stack* stack, int value) { if (isFull(stack)) { return 0; } stack->data[++stack->top] = value; return 1; }
int pop(Stack* stack, int* value) { if (isEmpty(stack)) { return 0; } *value = stack->data[stack->top--]; return 1; }
int getTop(Stack* stack, int* value) { if (isEmpty(stack)) { return 0; } *value = stack->data[stack->top]; return 1; }
int main() { Stack stack; int value; initStack(&stack); push(&stack, 1); push(&stack, 2); push(&stack, 3); getTop(&stack, &value); printf("栈顶元素为:%d\n", value); pop(&stack, &value); printf("弹出的元素为:%d\n", value); getTop(&stack, &value); printf("栈顶元素为:%d\n", value); return 0; }
|
2.链表形式堆栈的实现
(1)堆栈的定义以及结构体
1 2 3 4 5
| typedef struct node { int data; struct node* next; } Node;
|
(2)队列的基本操作的实现
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
| #include <stdio.h> #include <stdlib.h>
typedef struct node { int data; struct node* next; } Node;
typedef struct stack { Node* top; } Stack;
void init(Stack* s) { s->top = NULL; }
void push(Stack* s, int data) { Node* new_node = (Node*)malloc(sizeof(Node)); new_node->data = data; new_node->next = s->top; s->top = new_node; }
int pop(Stack* s) { if (s->top == NULL) { printf("Stack is empty.\n"); return -1; } int data = s->top->data; Node* temp = s->top; s->top = s->top->next; free(temp); return data; }
int top(Stack* s) { if (s->top == NULL) { printf("Stack is empty.\n"); return -1; } return s->top->data; }
int is_empty(Stack* s) { return s->top == NULL; }
void print_stack(Stack* s) { Node* current = s->top; printf("Stack: "); while (current != NULL) { printf("%d ", current->data); current = current->next; } printf("\n"); }
int main() { Stack s; init(&s);
push(&s, 1); push(&s, 2); push(&s, 3); int value = top(s); printf("%d \n",value); }
|