栈的链式存储结构

栈的链式存储结构

先上代码:

头文件:

#ifndef _STACK_H_
#define _STACK_H_

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

typedef int SElemType;

typedef struct StackNode
{
    SElemType data;
    struct StackNode* next;
}StackNode;

typedef struct StackNode* LinkStackPtr;

typedef struct LinkStack
{
    LinkStackPtr top;
    int counter;
}LinkStack;

void CreatStack(LinkStack* S);

int Push(LinkStack* S,SElemType e);

int Pop(LinkStack* S,SElemType* e);

void ClearStack(LinkStack* S);

void TraveStack(LinkStack* S);
#endif // _STACK_H_

具体实现:

#include "stack.h"

void CreatStack(LinkStack* S)
{
    S->top = NULL;
    S->counter = 0;
}

int Push(LinkStack* S,SElemType e)
{
    LinkStackPtr s = (LinkStackPtr)malloc(sizeof(StackNode));
    s->data = e;
    s->next = S->top;
    S->top = s;
    S->counter++;
    return 0;
}

int Pop(LinkStack* S,SElemType* e)
{
    LinkStackPtr p;
    if(S->counter == 0)
        return -1;
    *e = S->top->data;
    p = S->top;
    S->top = S->top->next;
    free(p);
    S->counter--;
    return 0;
}

void ClearStack(LinkStack* S)
{
    LinkStackPtr p,q;
    p = S->top;
    while(p)
    {
        q = p->next;
        free(p);
        p = q;
    }
    S->top = NULL;
    printf("Stack is clear");
}

void TraveStack(LinkStack* S)
{
    LinkStackPtr p;
    p = S->top;
    while(p)
    {
        printf("%d\n",p->data);
        p = p->next;
    }
}


测试:

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

#include "stack.h"

int main()
{
    int i;
    LinkStack S;
    CreatStack(&S);
    printf("The Stack's counter is %d\n",S.counter);
    printf("The Stack's top is OX%p\n",S.top);

    for(i = 0;i < 8;i++)
    {
        Push(&S,i);
    }

    printf("The Stack's counter is %d\n",S.counter);
    printf("The Stack's top is OX%p\n",S.top);
    TraveStack(&S);

    Pop(&S,&i);
    printf("i = %d is pop\n",i);

    printf("The Stack's counter is %d\n",S.counter);
    printf("The Stack's top is OX%p\n",S.top);
    TraveStack(&S);

    Pop(&S,&i);
    printf("i = %d is pop\n",i);

    printf("The Stack's counter is %d\n",S.counter);
    printf("The Stack's top is OX%p\n",S.top);
    TraveStack(&S);

    ClearStack(&S);

    return 0;
}

正文:

  • 栈是限定仅在一端进行插入和删除操作的线性表,又称为后进先出的线性表。
  • 栈顶放在单链表的头部比较合适。
  • 具体实现比较简单,看代码即可。