#include<stdio.h>
#include<stdlib.h>
struct node{
int info;
node *link;
};
node *top = NULL;
void push();
void pop();
void display();
main()
{
int choice;
while(1)
{
printf("Enter your choice:\n1.Push\n2.Pop\n3.Display\n4.Exit\n");
scanf("%d",&choice);
switch(choice)
{
case 1:
push();
break;
case 2:
pop();
break;
case 3:
display();
break;
case 4:
exit(1);
break;
default:
printf("Wrong choice");
}
// getch();
}
}
void push()
{
node *tmp;
int pushed_item;
tmp = new node;
printf("Enter the value to be pushed in the stack:");
scanf("%d",&pushed_item);
tmp->info=pushed_item;
tmp->link=top;
top=tmp;
}
void pop()
{
node *tmp;
if(top == NULL)
printf("Stack is empty");
else
{
tmp=top;
printf("Popped item is %d",tmp->info);
top=top->link;
delete tmp;
}
}
void display()
{
node *ptr;
ptr = top;
if(top==NULL)
printf("Stack is empty");
else
{
while(ptr != NULL)
{
printf("%d\n",ptr->info);
ptr=ptr->link;
}
}
}
每当我尝试创建一个新节点时,我都会遇到错误,例如
node *tmp;
tmp = new node;
错误在第二行。它在 TurboC++ 等其他 IDE 中正常工作,但在 Netbeans 中它给了我错误:“找不到声明的标识符。”
最佳答案
没有new
(和 delete
)C 中的运算符。您必须使用标准函数 malloc
(和 free
)声明为 union 国 header <stdlib.h>
相反。
考虑到这个结构定义
struct node{
int info;
node *link;
};
在 C 中无效。您必须使用标签 struct
在链接的定义中。例如
struct node
{
int info;
struct node *link;
};
C 和 C++ 中的函数 main 应具有返回类型 int
.
似乎 TurboC++ 将您的代码编译为 C++ 代码。
关于c - 为什么我无法在 C 中为我的结构创建新节点? (使用 Netbeans),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27022843/