吉安做网站的公司/创建网站的软件
堆栈的链式存储
- 1.结构体定义
- 2.初始化
- 3.是否为空
- 4.入栈
- 5.出栈
- 6.打印所有元素
- 8.测试
- 9.全部代码
1.结构体定义
typedef int ElementType;
typedef struct SNode *Stack;
struct SNode
{ElementType Data; //数据域struct SNode *Next; //指针域
};
2.初始化
只初始化头结点
Stack CreateStack()
{//构造一个堆栈的头结点并返回指针Stack S;S = (Stack)malloc (sizeof(struct SNode));S->Next = NULL;return S;
}
3.是否为空
判断:头结点指向空
int IsEmpty(Stack S)
{return S->Next ==NULL;
}
4.入栈
void Push(ElementType item,Stack S)
{struct SNode *tmp;tmp = (struct SNode *)malloc(sizeof(struct SNode ));tmp->Data = item;tmp->Next = S->Next;S->Next = tmp;
}
5.出栈
ElementType Pop(Stack S)
{struct SNode *firstcell; //记录需要删除的结点ElementType TopData; //需要返回的变量if(!IsEmpty(S)){firstcell = S->Next;TopData = S->Next->Data;S->Next = firstcell->Next;free(firstcell);return TopData;}else{printf("堆栈为空!");return NULL;}
}
6.打印所有元素
void print(Stack S)
{if(IsEmpty(S)){printf("堆栈为空!\n");return ;}Stack Pri = S->Next; while(Pri->Next!=NULL){printf("%d ",Pri->Data);Pri=Pri->Next;}printf("%d\n",Pri->Data);
}
8.测试
Stack s = CreateStack();print(s);Push(5,s);Push(23,s);Push(43,s);Push(565,s);Push(54,s);print(s);printf("删除的元素为:%d\n",Pop(s));print(s);
9.全部代码
#include<stdlib.h>
#include<stdio.h>
#include<malloc.h>
typedef int ElementType;typedef struct SNode *Stack;
struct SNode
{ElementType Data;struct SNode *Next;
};
//Stack S;
//初始化
Stack CreateStack()
{//构造一个堆栈的头结点并返回指针Stack S;S = (Stack)malloc (sizeof(struct SNode));S->Next = NULL;return S;
}int IsEmpty(Stack S)
{return S->Next ==NULL;
}//入栈
void Push(ElementType item,Stack S)
{struct SNode *tmp;tmp = (struct SNode *)malloc(sizeof(struct SNode ));tmp->Data = item;tmp->Next = S->Next;S->Next = tmp;
}//出栈
ElementType Pop(Stack S)
{struct SNode *firstcell; //记录需要删除的结点ElementType TopData; //需要返回的变量if(!IsEmpty(S)){firstcell = S->Next;TopData = S->Next->Data;S->Next = firstcell->Next;free(firstcell);return TopData;}else{printf("堆栈为空!");return NULL;}
}void print(Stack S)
{if(IsEmpty(S)){printf("堆栈为空!\n");return ;}Stack Pri = S->Next; while(Pri->Next!=NULL){printf("%d ",Pri->Data);Pri=Pri->Next;}printf("%d\n",Pri->Data);
}int main()
{Stack s = CreateStack();print(s);Push(5,s);Push(23,s);Push(43,s);Push(565,s);Push(54,s);print(s);printf("删除的元素为:%d\n",Pop(s));print(s);system("pause");return 0;
}