不带头结点:
#include<stdio.h>
#include<stdlib.h>
typedef struct Linknode{
int data;//一般写成ElemType data;
struct Linknode *next;
}SNode ,*LiStack;
//不带头结点的链栈初始化
bool InitStack(LiStack &S){
S=NULL;
return true;
}
//不含有头结点的头插法
bool Push(LiStack &S,int x){
SNode *addention=(SNode *)malloc(sizeof(SNode));
if(addention==NULL)
return false;
addention->data=x;
addention->next=S;
S=addention;
return true;
}
void print(LiStack &S){
SNode *temp=S;
while(temp!=NULL){
printf("%d ",temp->data);
temp=temp->next;
}
printf("\n");
}
bool Pop(LiStack &S,int &x){
//首先要检查是否为空
if(S==NULL)
return false;
x=S->data;
SNode *temp=S;
S=S->next;
free(temp);
return true;
}
int main(){
LiStack S;
int d;
InitStack(S);
for(int i=0;i<5;i++){
Push(S,i);
}
print(S);
Pop(S,d);
print(S);
printf("删除的数是:%d\n",d);
return 0;
}
带头结点
#include<stdio.h>
#include<stdlib.h>
typedef struct Linknode{
int data;//一般写成ElemType data;
struct Linknode *next;
}SNode ,*LiStack;
//带头结点的链栈初始化
bool InitStack(LiStack &S){
S=(SNode *)malloc(sizeof(SNode));
if(S==NULL)
return false;//创建失败
S->next=NULL;
return true;
}
//有头结点的头插法 实现入栈
bool Push(LiStack &S,int x){
SNode *addention=(SNode *)malloc(sizeof(SNode));
if(addention==NULL)
return false;
addention->data=x;
addention->next=S->next;
S->next=addention;
return true;
}
void print(LiStack &S){
SNode *temp=S->next;
while(temp!=NULL){
printf("%d ",temp->data);
temp=temp->next;
}
printf("\n");
}
bool Pop(LiStack &S,int &x){
//首先要检查是否为空
if(S->next==NULL)
return false;
x=S->next->data;
SNode *temp=S->next;
S->next=temp->next;
free(temp);
return true;
}
int main(){
LiStack S;
int d;
InitStack(S);
for(int i=0;i<5;i++){
Push(S,i);
}
print(S);
Pop(S,d);
print(S);
printf("删除的数是:%d\n",d);
return 0;
}