c - 终于用C实现了我的堆栈链表,但是有没有比我的更简单的方法?
问题描述
我终于建立了我的堆栈链表。它工作正常。但我想知道是否有比我的更简单、更短的方法。
我觉得..我的不是实现堆栈链表的最佳方式。
最好的方法:简单而简短。
我下面的整个代码..
#include <stdio.h>
#include <stdlib.h>
typedef int element;
typedef struct node{
element data;
struct node* next;
}node;
node* head = NULL;
void push(element data){
node* temp = (node*)malloc(sizeof(node));
if(temp==NULL)
printf("out of memory");
else{
temp->data = data;
temp->next = head;
printf("push(%d)\n", temp->data);
head = temp;
}
}
void pop(){
node* temp;
if(head==NULL) return;
temp = head;
head = temp->next;
free(temp);
}
void printStack(){
node* temp = head;
while(temp!=NULL){
printf("%d\n", temp->data);
temp = temp->next;
}
}
void is_Empty(){
if(head==NULL){
printf("EMPTY\n");
}
else{
printf("NOT EMPTY\n");
}
}
void main() {
push(10);
push(20);
push(30);
push(40);
printStack();
is_Empty();
}
解决方案
看起来不错,但通常当你弹出时,你想返回你删除的元素。另外,我会有一个释放堆栈的函数,这样如果你想创建一个抽象级别,人们仍然可以正确管理他们的内存。
推荐阅读
- javascript - 如何根据语义 UI 下拉列表中的选定项目更改页面上的文本?
- fullcalendar - 关于构建类似于 FullCalander 演示中显示的左侧菜单栏的建议
- java - 如何使用
- node.js - 如何安全地为 Web 应用程序创建管理员用户?
- python - 如何将 sh -c "$(curl -fsSL URL)" 转换为原生 python
- php - 类型提示所以属性是特定对象类型的数组
- mysql - 如何在 MySql 中使用 group by 查询非聚合列?
- reactjs - react-autosuggest 与 debounce 和 distinctUntilChanged
- python - 如何从安装在 CPanel 上的烧瓶应用程序生成错误日志?
- python - 带参数的 Ctypes 回调函数