算法导论 10.2-2

题目:使用链表实现栈,Push与Pop操作时间为O(1)

解答:

代码如下:

  1 /*
  2     ADT: 栈
  3     实现:带头结点的单链表
  4 */
  5 
  6 struct Node;
  7 typedef struct Node *PtrToNode;
  8 typedef PtrToNode Stack;
  9 
 10 struct Node
 11 {
 12     ElementType Element;
 13     PtrToNode Next;
 14 };
 15 
 16 /* 基本操作 */
 17 Stack CreatStack( );
 18 void DisposeStack( Stack S );
 19 int IsEmpty( Stack S );
 20 void MakeEmpty( Stack S );
 21 void Push( ElementType X, Stack S );
 22 void Pop( Stack S );
 23 ElementType Top( Stack S );
 24 
 25 
 26 Stack CreatStack( )
 27 {
 28     // 操作结果:返回空栈
 29 
 30     Stack S;
 31 
 32     S = ( Stack )malloc( sizeof(struct Node) );
 33     if ( NULL == S )
 34     {
 35         printf("Out of Space!!!");
 36         return NULL;
 37     }
 38 
 39     S->Next = NULL;
 40     MakeEmpty( S );
 41     return S;
 42 }
 43 
 44 void DisposeStack( Stack S )
 45 {
 46     // 操作结果:删除栈
 47     if ( S !== NULL )
 48     {    
 49         MakeEmpty( S );
 50         free( S );
 51     }
 52 }
 53 
 54 int IsEmpty( Stack S )
 55 {
 56     // 操作结果:判断栈是否为空
 57     return NULL == S->Next;
 58 }
 59 
 60 void MakeEmpty( Stack S )
 61 {
 62     // 操作结果:清空栈
 63 
 64     if ( NULL == S )
 65         printf("Must create stack first!");
 66     else
 67         while ( !IsEmpty(S) )
 68             Pop( S );
 69 }
 70 
 71 void Push( ElementType X, Stack S )
 72 {
 73     // 操作结果:使元素X入栈
 74     PtrToNode TmpCell;
 75 
 76     TmpCell = ( PtrToNode) malloc( sizeof(struct Node) );
 77     if ( NULL == TmpCell )
 78     {
 79         printf("Out of space!!!");
 80         return;
 81     }
 82 
 83     TmpCell->Element = X;
 84     TmpCell->Next = S->Next;
 85     S->Next = TmpCell;
 86 }
 87 
 88 void Pop( Stack S )
 89 {
 90     // 操作结果:若栈不为空,则使顶端元素出栈
 91 
 92     PtrToNode FirstCell;
 93 
 94     if ( IsEmpty(S) )
 95         printf("Empty Stack");
 96     else
 97     {
 98         FirstCell = S->Next;
 99         S->Next = FirstCell->Next;
100         free( FirstCell );
101     }
102 }
103 
104 
105 ElementType Top( Stack S )
106 {
107     // 操作结果:若栈不为空,则返回栈顶元素
108 
109     if ( !IsEmpty(S) )
110         return S->Next->Element;
111     printf( "Empty Stack" );
112     return 0;
113 }
原文地址:https://www.cnblogs.com/tallisHe/p/4032997.html