c - 使用链表将数据插入堆栈

标签 c linked-list stack

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

struct nodeStack{
    char operator;
    struct  nodeStack *next;

};

typedef struct nodeStack node;

node *start=NULL;
node *tail=NULL;
int top=-1;


int isEmpty()
{

    if(top==-1)
        return 1;

}



void push(char c){
    node *tempNode,*tail;

    tempNode=(node*) malloc(sizeof(node));
    if(tempNode==NULL){
        printf("Memory Unvailable\n");
        return;
    }

    tempNode->operator=c;
    if(start==NULL){
        start=tempNode;
        tail=start;
        tempNode->next=NULL;
        top++;
    }
    else{
        tail->next=tempNode;
        tempNode->next=NULL;
        tail=tail->next;
        top++;
    }

}


/*
struct node* pop(){
    if(top==-1){
        printf("stack is empty");
        return;
    }

    else
    {
        node *temp;
        temp=start;
        while(temp->next!=tail){
            temp->next=NULL;
            free(tail);
            tail=temp;
        }
    }

}*/


void displayStack(){
    node *i;
    for(i=start;i!=tail;i=i->next){
        printf("%c -> ",i->operator);
    }
}


int main(){
    int i;
    int flag=1;
    char choice='y';
    printf("pushing data into the stack......");

   while(flag==1){
        char ch;
        printf("enter a character\n");
        scanf(" %c",&ch);
        push(ch);
        printf("want to push more operator (y\n)");
        scanf(" %c",choice);
        if(choice=='y')
            flag=1;
        else
            flag=0;

   }

    displayStack();

   return 0; 
}

当我尝试运行它时,它给了我段错误。 它只接受一个输入并且不采取进一步的操作,同时它给出段错误

当我尝试运行它时,它给了我段错误。 它只接受一个输入并且不采取进一步的操作,同时它给出段错误

最佳答案

看一下:

scanf(" %c",choice);

第二个参数应作为地址传递,因为 scanf 会修改它。

尝试修改:

scanf("%c", &choice);

我不会详细解释原因,因为我认为你犯了一个错误,因为在前面的一些行 scanf("%c",&ch); 你已经调用了正确的方法.

注意:我会避免使用 scanf 字符串格式中的空格。

关于c - 使用链表将数据插入堆栈,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38991851/

相关文章:

c - 如果是c中的指针,函数的大小返回什么

Java List 如何设置和获取父类型列表的子对象

c - 如何在 C 中访问链表中的下一个元素?

c - 编写一个返回列表中字符串位置的函数(C 代码)

JAVA:简单弹出只返回第一项

c++ - c/c++中神经网络的实现方式是什么?

c - 翻译结构项的有效方法,避免 C 中的 switch-case

c - 套接字发送和接收缓冲区

c - LLDB会改变C程序的环境变量地址吗?

c - 一种破解 C 函数调用的快速方法