注意链栈没有栈满只有栈空的情况
因为满足先进后出的特点采用头插法 先进的在后面,后进的在前面,故出栈为出头结点的next;
#include <stdio.h>
//结构体
typedef struct Node{
int data;
struct Node * next;
}Node;
//初始化
void init(Node ** node){
(*node) = (Node*)malloc(sizeof(Node));
(*node)->next = NULL;//将node变成新的结点
}
//判断栈空
int isEmpty(Node * node){
if(node->next ==NULL){
return 1;
}else{
return 0;
}
}
//入栈
void push(Node * node,int x){
//头插法
Node * p = (Node*)malloc(sizeof(Node));
p->data = x;
p->next = NULL;
p->next = node->next;
node->next = p;
}
//出栈
`int pop(Node * node,int *x){
if(isEmpty(node)){//判断是否栈空
return 0;//栈空则出栈失败
}else{
Node * p = node->next;//将p指向头结点的next
node->next = p->next;//将头结点与p所指向的结点的连接断掉
(*x) = p->data;//将栈顶结点值赋值给x
free(p);//释放P结点
return 1;
}
}
//将10进制转换成16进制以下其余各进制,并打印
int change(int e,int size){//e代表数据 size代表进制
int new = 0;
int mod = 0;
int w;//用于接收出栈数据
Node* * node;
init(&node);//初始化链栈
while(e != 0){
mod = e%size;
e = e/size;
push=(node,mod);//入栈
}
while(!isEmpty(node)){//若栈不为空
pop(node,&w);//出栈
char c;
switch(w){
case 10:
c = 'A';
break;
case 11:
c = 'B';
break;
case 12:
c = 'C';
break;
case 13:
c = 'D';
break;
case 14:
c = 'E';
break;
case 15:
c = 'F';
break;
}
if(w>=10){
printf("%c",c);
}else{
printf("%d",w);
}
}
return new;
}