首页 > 解决方案 > 终于用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();
}

标签: cdata-structureslinked-liststack

解决方案


看起来不错,但通常当你弹出时,你想返回你删除的元素。另外,我会有一个释放堆栈的函数,这样如果你想创建一个抽象级别,人们仍然可以正确管理他们的内存。


推荐阅读