1. 程式人生 > >每天一個數據結構----棧的鏈式儲存結構實現(純程式碼)

每天一個數據結構----棧的鏈式儲存結構實現(純程式碼)

//

//  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;

}