[数据结构与算法分析] 栈的链表实现

前言

栈是一种较为简单而基础的数据结构,又叫LIFO(Last In Fisrt Out)表,也可以看做是一种限制插入和删除只能在一个位置上进行的表(这个位置就称为栈顶)。
栈的操作也很简单,大概就是Push, Pop和Top(有时叫GetTop)这几种操作。
这里采用单链表来实现栈,除此之外还可以用数组实现。

代码

.h文件声明:

#ifndef LINKSTACK_H_INCLUDED
#define LINKSTACK_H_INCLUDED

struct Node;
typedef struct Node *PtrToNode;
typedef PtrToNode Stack;

#define ElementType int

int IsEmpty(Stack S);
Stack CreateStack(void);
void MakeEmpty(Stack S);
void Push(ElementType X, Stack S);
ElementType Top(Stack S);
void Pop(Stack S);
void PrintStack(Stack S);
int StackSize(Stack S);

#endif // LINKSTACK_H_INCLUDED

.c文件实现:

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

struct Node{
  ElementType Element;
  PtrToNode Next;
};

int IsEmpty(Stack S) {  // Return 1 if stack is empty
  return S->Next == NULL;
}
Stack CreateStack(void) {
  Stack S = malloc(sizeof(S));
  if (S == NULL) {
    printf("Out of Space!\n");
  } else {
    S->Next = NULL;
    MakeEmpty(S);
    return S;
  }
}
void MakeEmpty(Stack S) {
  if (S == NULL) {
    printf("Must use CreateStack first!\n");
  } else {
    while (!IsEmpty(S))
      Pop(S);
  }
}
void Push(ElementType X, Stack S) {
  PtrToNode tmp = malloc(sizeof(tmp));
  if (tmp == NULL) {
    printf("Out of Space!\n");
  } else {
    tmp->Element = X;
    tmp->Next = S->Next;
    S->Next = tmp;
  }
}
ElementType Top(Stack S) {  // return -1 if stack is empty
  if (!IsEmpty(S)) {
    return S->Next->Element;
  } else {
    printf("Empty Stack!\n");
    return -1;
  }
}
void Pop(Stack S) {
  PtrToNode First;
  if (IsEmpty(S)) {
    printf("Empty Stack!\n");
  } else {
    First = S->Next;
    S->Next = S->Next->Next;
    free(First);
  }
}
void PrintStack(Stack S) {
  if (IsEmpty(S)) {
    printf("Empty Stack");
  } else {
    PtrToNode P = S->Next;;
    while (P != NULL) { // print all elements in stack by traversing linked list.
      printf("%d ",P->Element);
      P = P->Next;
    }
  }
  printf("\n");
}
int StackSize(Stack S) {
  int size = 0;
  if (!IsEmpty(S)) {
    PtrToNode P = S->Next; //here P is the top node
    while (P != NULL) { // print all elements in stack by traversing linked list.
      P = P->Next;
      size++;
    }
  }
  return size;
}

int main()
{
  Stack S1 = CreateStack();
  for (int i = 1; i <= 15; i++) {
    Push(i,S1);
  }

  PrintStack(S1);
  printf("%d\n",StackSize(S1));

  Push(100,S1);
  PrintStack(S1);
  printf("%d\n",StackSize(S1));

  MakeEmpty(S1);
  printf("%d",Top(S1));
}

测试运行结果

测试结果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值