本文主要是介绍数据结构手把手教学——链栈,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
一、链栈
1、top
:指向栈顶结点的指针,空栈时top = NULL
。
二、用C语言实现链栈
1、构造存储结构
typedef int datatype;typedef struct linkstack
{datatype data;struct linkstack *next;
}link_stack, *link_pstack;
2、初始化
初始化让
top = NULL;
void init_linkstack(link_pstack *top)
{(*top) = NULL;
}
3、入栈
new->next = top;
top = new;
void push_linkstack(link_pstack *top, datatype dat)
{link_pstack new = NULL;new = (link_pstack)malloc(sizeof(link_stack));if (NULL == new){perror("malloc");return;}new->data = dat;new->next = (*top);(*top) = new;
}
4、出栈
出栈之前需要判断栈是否为空
t = top;
t
top = top->next;
top= top->next;
free(t);
(1)、判断栈是否为空
判断top是否为NULL即可
bool isempty_linkstack(link_pstack top)
{if (NULL == top){return true;}else{return false;}
}
(2)、出栈
void pop_linkstack(link_pstack *top, datatype *dat)
{link_pstack t = NULL;if (isempty_linkstack(*top)){printf("栈已空\n");return;}t = (*top);(*dat) = t->data; //保存出栈的数据(*top) = (*top)->next;free(t);
}
5、打印
void show_linkstack(link_pstack top)
{link_pstack p = NULL;for (p = top; p != NULL; p = p->next){printf("%d\t", p->data);}printf("\n");
}
三、练习题
用链栈实现十进制向八进制转换。例如输入123,输出0173
1、实现代码
int main(void)
{link_pstack top = NULL;datatype data_push = 0;datatype data_temp = 0;datatype data_pop = 0;init_linkstack(&top);printf("输入十进制数:");scanf("%d", &data_push);data_temp = data_push;if (data_push < 0){data_push = -data_push;}while (data_push){push_linkstack(&top, data_push%8);data_push = data_push/8;}if (data_temp < 0){printf("十进制数: %d的八进制为:-0", data_temp);}else{printf("十进制数: %d的八进制为:0", data_temp);}while (!isempty_linkstack(top)){pop_linkstack(&top, &data_pop);printf("%d", data_pop);}printf("\n");return 0;
}
2、结果
四、完整代码
https://github.com/sanjaywu/DataStructure
这篇关于数据结构手把手教学——链栈的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!