【问题标题】:Confused with stack using a singly linked list对使用单链表的堆栈感到困惑
【发布时间】:2016-02-23 07:49:08
【问题描述】:

这是我到目前为止所做的,我对链表和堆栈还很陌生,所以它们让我有点困惑,我正在尝试弄清楚如何执行我的 isempty 函数,它应该是如果为空,则给我 1,如果不为空,则给我 0。

#include <stdio.h>
#include <stdlib.h>

typedef struct stack node;
typedef struct stack *link;

struct stack
{
   int val;
  link next;
};

// Global top variable
link top = NULL;


void push(int n)
{
  link tmp;
  tmp = malloc(sizeof(node));

  tmp->val = n;
  tmp->next = top;
  top = tmp;
}

int pop()
{
  int val = top->val;
  link tmp = top;
  top = top->next;
  free(top);

  return val;
}

int isempty()
{

}


void printstack()
{
  link tmp = top;

  while (tmp != NULL)
  {
      printf("%2d ", tmp->val);
      tmp = tmp->next;
  }
}

int main()
{
  int x, i, j;
  printf("Enter an integer: ");
  scanf("%2d ", &x);

  return 0;
}

【问题讨论】:

  • 看起来你可以简单地使用if(top),因为当堆栈为空时top 将等于NULL
  • 抱歉,我在这方面不是最擅长的,所以你说'if (top == NULL)' 返回你的 1 值,否则返回你的 0 值,对吗?
  • 正确,int isempty(){return (top == NULL) ? 1 : 0;} 或简单的int isempty(){return (top == NULL);}
  • 嗯,好的,谢谢,这很有道理。
  • 是的,我的错。对于isempty(),我的建议应该是!top,但无论如何我希望它有所帮助。

标签: c stack singly-linked-list


【解决方案1】:

首先,函数 pop 似乎有一个错字

int pop()
{
  int val = top->val;
  link tmp = top;
  top = top->next;
  free(top);
  ^^^^^^^^^
  return val;
}

必须有free( tmp ) 而不是free( top )

你还应该检查函数内部的堆栈是否为空。

我认为最好按以下方式定义函数

int pop( int *value )
{
    int success;

    if ( ( success = top != NULL ) )
    {
        *value = top->val;

        link tmp = top;
        top = top->next;
        free( tmp );
    }

    return success;
}

至于函数isempty`那么它的实现很简单

int isempty()
{
    return top == NULL;
}

【讨论】:

    猜你喜欢
    • 2012-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多