堆栈的定义与操作——顺序存储和链式存储

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

  说明:假设 ElementType 是一个指针类型

  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; 
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;
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 }

  

猜你喜欢

转载自www.cnblogs.com/wgxi/p/9973919.html