1 void Pop(Stack S)
 2 {
 3     PtrToNode FirstNode;
 4     if(IsEmpty(S))
 5         Error("Empty Stack");
 6     else
 7     {
 8         FirstCell=S->Next;
 9         S->Next=S->Next->Next;
10         free(FirstCell);
11     }
12 }
View Code

 

栈是限制插入和删除只能在一个位置上进行的表,该位置是表的末端,叫做栈的顶;

一、栈的链表实现

1.栈ADT的链表实现的类型声明

 1 #ifndef _Stack_h
 2 strut Node;
 3 typedef struct Node *PtrNode;
 4 typedef PtrNode Stack;
 5 
 6 int IsEmpty(Stack S);
 7 Stack CreaeStack(void);
 8 void DisposeStack(Stack S);
 9 void MakeEmpty(Stack S);
10 void Push(ElementType X,Stack S);
11 ElementType Top(Stack S);
12 void Pop(Stack S);
13 #endif
14 
15 struct Node
16 {
17   ElementType Element;
18   PtrNode Next;
19 }

 2、测试栈是否为空

1 int IsEmpty(Stack S)
2 {
3   return S->Next==NULL;  
4 }
View Code

3、创建空栈

 1 Stack CreateStack(void)
 2 {
 3     Stack S;
 4     S=malloc(sizeof(Struct Node));
 5     if(S==NULL)
 6         FatalError("Out of space!");
 7     S->Next=NULL;
 8     MakeEmpty(S);
 9     return S;
10 }
11 
12 void MakeEmpty(Stack S)
13 {
14     if(S==NULL)
15         Error("Must create stack firs");
16     else
17         while(!IsEmpty(S))
18             Pop(S);
19 }
View Code

4、进栈

 1 void Push(ElementType x,Stack S)
 2 {
 3     PtrToNode TmpCell;
 4     TmpCell=malloc(sizeof(struct Node));
 5     if(TmpCell==NULL)
 6         FatalError("Out of space");
 7     else
 8     {
 9         TmpCell->Element=x;
10         TmpCell->Next=S->Next;
11         S->Next=TmpCell;
12     }
13 }
View Code

5、返回栈顶元素

1 ElementType Top(Stack S)
2 {
3     if(!IsEmpty(S))
4         return S->Next->Element;
5     Error("Empty Stack");
6     return 0;
7 }
View Code

6、出栈

 1 void Pop(Stack S)
 2 {
 3     PtrToNode FirstNode
 4     if(IsEmpty(S))
 5         Error("Empty Stack");
 6     else
 7     {
 8         FirstNode=S->Next;
 9         S->Next=S->Next->Next;
10         free(FirstNode);
11     }
12 }
View Code

 

 

posted on 2013-05-25 16:05  drakeTT  阅读(231)  评论(0)    收藏  举报