C语言栈的实现

近期在研究java内存管理的时候经常碰到堆、栈等数据结构方面的内容。堆、栈的相关内容很久已经没有温习,因此这里决定用C语言进行一些简单的实现,方便以后自己查看。在温习基础数据结构的同时也温习一下C语言。废话不说了直接上代码。

stack.h

#include
#include

typedef struct node {
    char *name;
    int grade;
    int age;
    struct node *next;
} *StackNode, node;

typedef struct Stack {
    StackNode top;
    StackNode bottom;
} Stack;

//初始化栈
void init(Stack *pstack);
//压栈
void push(Stack *pstack, StackNode pnode );
//弹栈
StackNode pop(Stack *pstack);
//是否为空
int isEmpty(Stack *pstack);
//清空
void ClearAll(Stack *pstack);

下面是压栈、弹栈、清空、遍历等操作的具体实现

#include"stack.h"

void init(Stack *pstack) {
    pstack->top  = (StackNode)malloc(sizeof(node));
    if (pstack->top == NULL) {
        printf("分配内存失败!\n");
        return;
    }

    pstack->bottom = pstack->top;
    pstack->top->next = NULL;
}

int isEmpty(Stack *pstack) {
    
    if (pstack == NULL) {
        printf("栈不存在! \n");
        return 0;
    }
    else {
        if (pstack->top == pstack->bottom)
            return 1;
        else 
            return 0;
    }
}

void push(Stack *pstack, StackNode pnode) {
    if (pstack == NULL)
        printf("错误:栈不存在!\n");
    pnode->next = pstack->top;
    pstack->top = pnode;
}

StackNode pop(Stack *pstack) {
    StackNode result = NULL;
    if (isEmpty(pstack)) {
        printf("栈为空,弹栈失败!\n");
    }
    else {
        result = pstack->top;
        pstack->top = pstack->top->next;
    } 
    return result;
}

void ClearAll(Stack *pstack) {
    if (isEmpty(pstack))
        return;
    StackNode p = pstack->top;
    StackNode q = NULL;

    while(p != pstack->bottom) {
        q = p->next;
        free(p);
        p = q;
    }
    pstack->top = pstack->bottom;
}

void print(Stack *pstack) {
    if (pstack == NULL)
        printf("错误:栈不存在!");
    else if (pstack->top == pstack->bottom) {
        printf("栈为空!\n");    
    }
    else {
        StackNode p = pstack->top;
        while (p != pstack->bottom) {
            printf("姓名:%s\t年级:%d\t年龄:%d\n",p->name, p->grade, p->age);
            p = p->next;
        }
    }
}

int main() {
    Stack *pstack;
    init(pstack);
    StackNode pnode = (StackNode)malloc(sizeof(node));
    pnode->name = "karno";
    pnode->grade = 100;
    pnode->age = 23;
    
    push(pstack, pnode);
    print(pstack);

    StackNode result = pop(pstack);
    print(pstack);

    
    return 0;
}

你可能感兴趣的:(C语言栈的实现)