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

前言

栈是一种较为简单而基础的数据结构,又叫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));
}

测试运行结果

[数据结构与算法分析] 栈的链表实现_第1张图片

你可能感兴趣的:(数据结构,链表,栈)