栈又称堆栈,仅允许在表的一端进行插入和删除操作的线性表,该位置位于表尾,称为栈顶(Top),相对地,另一端称为栈底。由于栈的插入和删除运算只能在栈顶一端进行,后进栈元素必定先出栈,所以把栈称为后进先出表(last in first out 简称 LIFO)
这里使用链表实现栈

栈的定义
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| struct Node; typedef struct Node *PtrToNode; typedef PtrToNode Stack; typedef int ElementType; 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);
typedef int ElementType; struct Node{ ElementType Element; PtrToNode Next; };
|
栈的实现
栈的主要操作集中在Push和Pop操作,前者向栈中压入一个数据,后者从栈中弹出一个数据
Push功能实现
1 2 3 4 5 6 7 8
| void Push(ElementType X,Stack S){ PtrToNode Node; Node = (PtrToNode)malloc(sizeof(struct Node)); if(Node == NULL) return; Node->Element = X; Node->Next = S->Next; S->Next = Node; }
|
Pop功能实现
1 2 3 4 5 6 7
| void Pop(Stack S){ if(IsEmpty(S)) return; PtrToNode temp = S->Next; S->Next = temp->Next; temp->Next = NULL; free(temp); }
|
参考源码