每天一个数据结构----栈的链式存储结构实现(纯代码)

版权声明:原创文章,转载请注明原文地址。 https://blog.csdn.net/it_r00t/article/details/80062170
//

//  main.c

//  StackList2 栈的链式存储结构

//

//  Created by Jacobs.Guo on 2018/4/23.

//  Copyright © 2018年 yage guo. All rights reserved.

//



#include <stdio.h>

#include <stdlib.h>



#define OK 1

#define ERROR 0

#define TRUE 1

#define FALSE 0

typedef int status;

typedef char SelemType;

typedef struct Snode{

    SelemType data;

    struct Snode *next;

}Snode,*Slink;



typedef struct LinkStack{

    Slink top;

    int count;

}LinkStack;

//初始化链栈

status InitLinkStack(LinkStack *L)

{

    L->top = (Slink)malloc(sizeof(Slink));

    

    if(!L->top) return ERROR;

    L->top = NULL;

    L->count = 0;

    

    return OK;

}

//将e压入栈S中

status Push(LinkStack *L,SelemType e)

{

    Slink p;

    p = (Slink)malloc(sizeof(Slink));

    

    p->data = e;

    p->next = L->top;

    L->top = p;

    L->count++;



    return OK;

}

//visit

status visit(SelemType c)

{

    printf("%c ",c);

    return  OK;

}

//由栈顶至栈顶打印栈的元素

status LinkTraver(LinkStack *L)

{

    Slink p;

    p = L->top;

    while (p){

        visit(p->data);

        p = p->next;

    }

    printf("\n");

    return OK;

}

//返回栈长度

int LinkLength(LinkStack L)

{

    return L.count;

}

//判断栈是否为空

status LinkEmpty(LinkStack *L)

{

    if (L->count) return FALSE;

    else return TRUE;

}

//栈顶元素出栈

status Pop(LinkStack *L,SelemType *e)

{

    Slink p;

    if (LinkEmpty(L)) return ERROR;

    

    *e = L->top->data;

    p = L->top;

    

    L->top = L->top->next;

    free(p);

    L->count--;

    

    

    return OK;

}

/* 把S置为空栈 */

status ClearStack(LinkStack *L)

{

    Slink p,q;

    p=L->top;

    while(p)

    {

        q=p;

        p=p->next;

        free(q);

    }

    L->count=0;

    return OK;

}



int main() {

    LinkStack S;

    int i;SelemType e;

    printf("初始化栈S...\n");

    InitLinkStack(&S);

    

    printf("将元素a,b,c,d,e,f顺序做入栈操作...\n");

    for (i = 0 ;i<6;i++)

        Push(&S, 'a'+i);

    

    printf("栈元素个数:%d\n",LinkLength(S));

    printf("遍历栈元素...\n");

    LinkTraver(&S);

    printf("\n");



    Pop(&S,&e);

    printf("栈顶元素:%c出栈\n",e);

    printf("栈元素个数:%d\n",LinkLength(S));

    printf("遍历栈元素...\n");

    LinkTraver(&S);

    printf("\n");

    

    

    Pop(&S,&e);

    printf("栈顶元素:%c出栈\n",e);

    printf("栈元素个数:%d\n",LinkLength(S));

    printf("遍历栈元素...\n");

    LinkTraver(&S);



    printf("\n");

    ClearStack(&S);

    printf("栈S已经被清空...\n");

    return 0;

}

猜你喜欢

转载自blog.csdn.net/it_r00t/article/details/80062170