zoukankan      html  css  js  c++  java
  • 堆栈的定义与操作——顺序存储和链式存储

      堆栈 的 存储结构 顺序存储链式存储

      1. 堆栈的顺序存储和操作

     1 typedef int Position;
     2 struct SNode {     
     3     ElementType *Data;    // 存储元素 的数组 
     4     Position Top;        // 栈顶 指针 
     5     int Cap;             // 堆栈最大容量 
     6 };
     7 typedef struct SNode *Stack;
     8 
     9 // 操作集
    10 Stack CreateStack(int MaxSize);
    11 void Push(Stack S, ElementType X);
    12 int IsEmpty(Stack S);
    13 int IsFull(Stack S);
    14 ElementType Pop(Stack S);
    15 
    16 Stack CreateStack(int MaxSize)
    17 {
    18     Stack S = (Stack)malloc(sizeof(struct SNode));
    19     S->Data = (ElementType*)malloc(MaxSize * sizeof(ElementType));
    20     S->Top = -1;    S->Cap = MaxSize;
    21     
    22     return S;
    23 }
    24 
    25 int IsEmpty(Stack S)
    26 {
    27     return ( S->Top == -1 );
    28 }
    29 
    30 int IsFull(Stack S)
    31 {
    32     return ( S->Top == S->Cap-1 );
    33 }
    34 
    35 void Push(Stack S, ElementType X)
    36 {
    37     if ( IsFull(S) )    return;
    38     
    39     S->Data[++(S->Top)] = X;
    40 }
    41 
    42 ElementType Pop(Stack S)
    43 {
    44     if ( IsEmpty(S) ) return NULL;  // 这里的返回值应该视具体情况而定(可能返回 NULL,或者返回 ElementType 类型)
    45     
    46     return    S->Data[(S->Top)--];
    47 }

       2. 堆栈的链式存储和操作

     1 typedef struct SNode *PtrToNode;
     2 struct SNode {
     3     ElementType Data;
     4     PtrToNode Next;
     5 };
     6 typedef PtrToNode Stack;
     7 
     8 // 操作集
     9 Stack CreateStack();
    10 void Push(Stack S, ElementType X);
    11 int IsEmpty(Stack S);
    12 ElementType Pop(Stack S);
    13 
    14 Stack CreateStack()
    15 {    // 创建一个堆栈的头节点,返回该节点指针 
    16     Stack S = (Stack)malloc(sizeof(struct SNode));
    17     S->Next = NULL;
    18     
    19     return S;
    20 }
    21 
    22 int IsEmpty(Stack S)
    23 {
    24     return ( S->Next == NULL );
    25 }
    26 
    27 void Push(Stack S, ElementType X) 
    28 {
    29     PtrToNode TmpCell = (PtrToNode)malloc(sizeof(struct SNode));
    30     TmpCell->Data = X;
    31     TmpCell->Next = S->Next;
    32     S->Next = TmpCell;
    33 }
    34 
    35 ElementType Pop(Stack S)
    36 {
    37     if ( IsEmpty(S) )    return NULL; // 这里的返回值应该视具体情况而定(可能返回 NULL,或者返回 ElementType 类型)
    38     
    39     ElementType TopElem;
    40     PtrToNode FrontCell;
    41     
    42     FrontCell = S->Next;
    43     TopElem = FrontCell->Data;
    44     
    45     S->Next = FrontCell->Next;
    46     free(FrontCell);
    47     
    48     return TopElem;
    49     
    50 }

      

  • 相关阅读:
    只要你拥有爱心,你就会拥有快乐。
    解决升级 Office 2010 之后 Outlook 提示“无法打开 Microsoft Outlook”
    《老人与海》
    UML模型的组成
    2009年11月11日
    IBatis存取图片在Oracle Blob大字段中Asp.Net
    “北京今年入冬的第一场雪”,纪念博客园写日志一年了
    UML建模实践概述
    UML 类图
    UML 用例图
  • 原文地址:https://www.cnblogs.com/wgxi/p/9973919.html
Copyright © 2011-2022 走看看