C语言链表实现栈

/**
    链表实现带头结点的栈,入栈用头插法
    环境codeblocks
*/

#include 
#include 
#include 

typedef int ElemType;
typedef struct Node {
    ElemType data;
    struct Node *next;
} Node, *LinkStack;

//初始化栈
LinkStack initStack(LinkStack s);

//入栈
bool pushStack(LinkStack s, ElemType e);

//出栈
Node* popStack(LinkStack s);

//打印栈
void printStack(LinkStack s);

//判空
bool isEmptyStack(LinkStack s);

//获取栈元素个数
int getLength(LinkStack s);

//初始化栈
LinkStack initStack(LinkStack s) {
    s = (LinkStack) malloc(sizeof(Node));
    s->next = NULL;
    return s;
}

//入栈
bool pushStack(LinkStack s, ElemType e) {
    Node *p = (LinkStack) malloc(sizeof(Node));
    if(!p) return false;
    p->data = e;
    p->next = s->next;
    s->next = p;
    return true;
}

//出栈
Node* popStack(LinkStack s) {
    Node *p = s->next;
    if(p!=NULL) {
        s->next = p->next;
    }
    return p;
}

//打印栈
void printStack(LinkStack s) {
    Node *p = s->next;
    while(p!=NULL) {
        printf("stack elem: %d\n",p->data);
        p = p->next;
    }
}

//判空
bool isEmptyStack(LinkStack s) {
    if( !s || s->next == NULL) return true;
    return false;
}

//获取栈元素个数
int getLength(LinkStack s) {
    Node *p = s->next;
    int i= 0;
    while(p!=NULL) {
        i++;
        p=p->next;
    }
    return i;
}

int main()
{
    LinkStack S = initStack(S);
    pushStack(S,1);
    pushStack(S,2);
    pushStack(S,3);
    pushStack(S,4);
    printStack(S);
    printf("pop elem is %d\n",popStack(S)->data);
    printf("pop elem is %d\n",popStack(S)->data);
    printf("pop elem is %d\n",popStack(S)->data);
    printf("pop elem is %d\n",popStack(S)->data);

    printf("stack length %d\n",getLength(S));
}

运行结果:

C语言链表实现栈_第1张图片

你可能感兴趣的:(数据结构)