第三章代码
不知不觉已经第三章了。坚持更新,虽然可能看到的人比较少。人气也不高。但是知道自己懂了进步了就可以了。
栈(用顺序表实现栈)
#include<stdio.h>
#define Maxsize 10
//定义栈结构
typedef struct{
int data[Maxsize];//数组
int top;//逻辑上充当栈指针
}SqStack;
//初始化栈
void Initstack(SqStack &S){
S.top=-1;
}
//判空
bool Emptystack(SqStack S){
if(S.top==-1) return true;
else return false;
}
//入栈,把元素压入栈顶;
bool Push(SqStack &S,int e){
if(S.top==Maxsize) return false;
S.top=S.top+1;
S.data[S.top]=e;
return true;
}
//出栈,把栈顶元素弹出
bool Pop(SqStack &S,int &e){
if(S.top==-1) return false;
e=S.data[S.top];
S.top=S.top-1;
return true;
}
//获取栈顶数据;
bool GetTopelem(SqStack S,int &e){
if(S.top==-1) return false;
e=S.data[S.top];
return true;
}
int main(){
SqStack S;
return 0;
}
这一块代码有点简单了。没什么好注释的了。听王道的课自己敲一遍就很简单。
单链表实现栈
注意点挺多的还;基本逻辑应该没啥问题的,听过课就能懂!!!
自己动动手哈!!!
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
typedef struct Linknode{
int data;
struct Linknode * next;
}Linknode,*Listack;
//初始化栈
bool InitListack(Listack &S){
S = (Linknode *) malloc(sizeof(Linknode));//申请内存
if(S->next==NULL) return false;//申请失败
S->data = 0;//初始化链栈头结点数据域
S->next = NULL;//初始化链栈头结点指针域
return true;
}
//入栈
bool Push(Listack &S,int e){
Linknode *headpoint;//指向新节点的指针
headpoint=(Listack)malloc(sizeof(Linknode));//分配空间
if(headpoint==NULL) return false;//申请空间失败
if(S->next==NULL){
headpoint->data=e;//给节点赋值
headpoint->next=NULL;//链接新节点
S->next=headpoint;
return true;
}else{
headpoint->data=e;//给节点赋值
headpoint->next=S->next;//链接新节点
S->next=headpoint;
return true;
}
}
//出栈
bool Pop(Listack &S,int &e){
Linknode *headpoint=S->next;//指向出栈节点的指针
if(S->next==NULL) return false;//空栈,没有节点可以出栈了
else{
//头结点链接第二个元素节点
e=headpoint->data;
S->next=headpoint->next;
free(headpoint);
return true;
}
}
bool Emptystack(Listack S){
if(S->next==NULL) return true;
else return false;
}
int main(){
Listack S;
InitListack(S);
int x,e;
printf("请输入一个值0退出;1表示出栈;2表示入栈:\n");
scanf("%d",&x);
while(x!=0){
if(x==1){
printf("新节点值输入:\n");
scanf("%d",&e);
Push(S,e);
}
if(x==2){
if(!Emptystack(S)){
Pop(S,e);
printf("出栈节点值:%d\n",e);
}
else printf("出栈失败!!");
}
printf("请输入一个值0退出;1表示出栈;2表示入栈:\n");
scanf("%d",&x);
}
return 0;
}
运行演示
代码写半小时调优1小时,心酸!!!!且行且珍惜!