[數據結構與算法分析] 棧的鏈表實現

前言

棧是一種較爲簡單而基礎的數據結構,又叫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));
}

測試運行結果

測試結果

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章