【问题标题】:How to link stacks to other stacks using Linked List in C programming?如何在 C 编程中使用链表将堆栈链接到其他堆栈?
【发布时间】:2018-06-10 12:52:46
【问题描述】:

我使用链表制作了自己的堆栈。但我认为这是错误的。 我的推送方法是将 Stack1 链接到其他堆栈。 所以,我认为它就像......

In my main function,

push(stack1, 10);
push(stack1, 20);

[Stack1] -> [nextStack]
[Stack1] -> [nextStack] (new address from first nextStack)

所以,就像...我一次又一次地重复将 stack1 链接到其他堆栈...

这是我使用下面的链表代码的堆栈。

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

typedef struct{
    int data;
   struct stack *top;
}stack;

void push(stack *currentStack, int data){

    if (currentStack->top == NULL)
        fprintf(stderr, "Stack is emtpy");

    else{
        stack *nextStack = (stack*)malloc(sizeof(stack));
        currentStack->data = data;
        currentStack->top = nextStack;

        printf("currentStack is %d\n", currentStack->data);
    }
}

int main(){

    stack* stack1;
    stack1 = (stack*)malloc(sizeof(stack));

    push(stack1, 10);
    push(stack1, 20);

    return 1;
}

这是我的代码的结果。

currentStack is 10
currentStack is 20

【问题讨论】:

  • 至少你永远不会初始化你分配的结构,所以当你使用它时你会得到未定义的行为。使用调试器会立即向您展示这一点,因此请从一开始就学习如何使用它。
  • @Sami 好的。我觉得我没有任何基础。真的感谢。我会调查的!

标签: c data-structures linked-list stack


【解决方案1】:
#include <stdio.h>
#include <stdlib.h>

struct stack
{
    int data;
    struct stack *top;
}  *head = NULL;


void push(int data)
{
    if (head == NULL)   //that means stack is empty
    {
        head =(struct node *)malloc(1*sizeof(struct node));
        head->top = NULL;
        head->data = data;
    }
    else
    {
        temp =(struct node *)malloc(1*sizeof(struct node));
        temp->top = head;
        temp->data = data;
        head = temp;
    }

}

您的 push() 函数不完整。 它应该考虑两种情况,一种是堆栈为空,一种是非堆栈。

另外,在 push() 函数中也不需要传递 pointer-to-stack,因为 push() 函数默认将新元素推送到最顶层节点而且只有一层。

你还没有用 NULL 初始化你的堆栈指针。这可能会在程序运行期间给您带来未定义的行为。

【讨论】:

  • "另外,也不需要在 push() 函数中传递指向堆栈的指针,因为 push() 函数默认将新元素推送到最顶层节点上,并且只有一个堆栈。 - 即使在特定的应用程序中,只需要一个堆栈,将数据结构设计为一个单一的全局数据结构也是不灵活的,并且会引发各种错误。永远不要将数据结构设计为单一的全局变量!
  • 从好的方面来说,您的代码应该可以工作。我想至少在原始代码中提及失败的实际原因会有所帮助:堆栈最多包含一个元素,并且每个 push() 都只是覆盖了堆栈中的旧元素(好吧,丢弃它会造成内存泄漏...)。关于:“您的 push() 函数不完整。应该考虑两种情况,一种是堆栈为空,另一种不是堆栈。” - 是的,是吗?
猜你喜欢
  • 2016-07-01
  • 2012-09-30
  • 2012-10-25
  • 2012-10-14
  • 1970-01-01
  • 1970-01-01
  • 2012-05-24
  • 2019-03-04
  • 2020-01-16
相关资源
最近更新 更多