C语言,栈,顺序栈,链栈

顺序栈:

/*===============================================
*   文件名称:seqinn.c
*   创 建 者:WM
*   创建日期:2023年08月19日
*   描    述:顺序栈
================================================*/
#include <stdio.h>
#include<stdlib.h>
#include<string.h>

#define SIZE 6
typedef int data_t;
typedef struct node
{
    data_t data[SIZE];
    data_t Top;
}stack;
//头
stack *create_dlinklist()
{
    stack *head=(stack*)malloc(sizeof(stack));
    head->Top=-1;
    memset(head->data,0,sizeof(head->data));
    return head;
}
//判空:head->Top==-1
int stack_is_empty(stack * head)
{
    if(head==NULL) return -1;
    return (head->Top==-1)?1:0;
}
//判满head->Top+1=SIZE;
int stack_is_full(stack * head)
{
    if(head==NULL) return -1;
    return (head->Top+1==SIZE)?1:0;
}
//入栈
int insart_stack(stack* head,data_t val)
{
    if(head==NULL) return -1;
    if(stack_is_full(head)==1) return -1;
    head->Top++;
    head->data[head->Top]=val;
    printf("%d ",val);
    return 0;
}
//出栈s
int out_stack(stack *head)
{
     if(head==NULL) return -1;
    if(stack_is_empty(head)==1) return -1;
    data_t val=head->data[head->Top];
    printf("%d ",val);
    head->Top--;
    return val;
}
int main(int argc, char *argv[])
{ 
    stack *phead=create_dlinklist();
    for (int i = 0; i < SIZE; i++)
    {
        insart_stack(phead,i+1);
    }
    for (int i = 0; i < SIZE; i++)
    {
        out_stack(phead);
    }
    return 0;
} 

链表栈:

注意链表的特性与栈的特性。

#include <stdio.h>
#include <stdlib.h>

// 定义链表节点
typedef struct Node {
    int data;
    struct Node* next;
} Node;

// 定义栈结构
typedef struct Stack {
    Node* top;
} Stack;

// 初始化栈
void initializeStack(Stack* stack) {
    stack->top = NULL;
}

// 检查栈是否为空
int isEmpty(Stack* stack) {
    return stack->top == NULL;
}

// 压入元素到栈顶
void push(Stack* stack, int value) {
    Node* newNode = (Node*)malloc(sizeof(Node));
    if (!newNode) {
        printf("Memory error\n");
        return;
    }
    newNode->data = value;
    newNode->next = stack->top;
    stack->top = newNode;
}

// 弹出栈顶元素
int pop(Stack* stack) {
    if (isEmpty(stack)) {
        printf("Stack underflow\n");
        return -1;  // 可以通过错误码或其他方式处理这种情况
    }

    Node* temp = stack->top;
    int poppedValue = temp->data;
    stack->top = stack->top->next;
    free(temp);
    
    return poppedValue;
}

// 查看栈顶元素
int peek(Stack* stack) {
    if (isEmpty(stack)) {
        printf("Stack is empty\n");
        return -1;  // 可以通过错误码或其他方式处理这种情况
    }
    return stack->top->data;
}

// 释放栈
void freeStack(Stack* stack) {
    while (!isEmpty(stack)) {
        pop(stack);
    }
}

int main() {
    Stack stack;
    initializeStack(&stack);

    push(&stack, 10);
    push(&stack, 20);
    push(&stack, 30);

    printf("Top element: %d\n", peek(&stack));
    printf("Popped element: %d\n", pop(&stack));
    printf("Top element after pop: %d\n", peek(&stack));

    freeStack(&stack);

    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_52119661/article/details/132392793