在链表前面插入节点
Inserting node in front of Linked List
下面的代码应该在链表的前面添加一个节点并打印当前元素。但是运行此代码会给我运行时错误,程序终止。当询问有多少个数字时,我输入了一个数字,然后它显示"main.cpp已停止工作"。可能出了什么问题?
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
struct Node
{
int data;
Node* next;
};
struct Node* head;
using namespace std;
void Insert(int x)
{
Node* temp=new Node();
temp->data=x;
temp->next=head;
head=temp;
}
void Print()
{
Node* temp1=head;
while(temp1!=NULL)
{
printf("%dn",temp1->data);
temp1=temp1->next;
}
printf("n");
}
int main()
{
head=NULL;
printf("how many numbers?n");
int n,i,x;
scanf("%d",n);
for(i=0;i<n;i++)
{
printf("Enter the number: n");
scanf("%d",x);
Insert(x);
Print();
}
return 0;
}
这甚至不是一个链表问题:
int n,i,x;
scanf("%d",n);
应该是
int n,i,x;
scanf("%d",&n);
(下面还有另一个出现)
因为扫描整数需要它们的地址,而不是字符串。
相关文章:
- C++17 - 使用自定义分配器的节点提取/重新插入 - 适用于 clang++/libc++,但不适用于 libstd
- 将二叉树的节点插入链表 (C++)
- 如何在使用 ItemType 的模板类时将新节点插入二叉树 c++.(我是 c++ 的新手)
- 单个链表,节点插入最低到最高节点值的问题
- 无法将节点插入C 中的链接列表中
- 将节点插入链表只会转到开头或结尾
- 将节点插入 BST
- 按排序顺序将节点插入链表
- LinkedList节点插入
- 二进制搜索树节点插入
- 使用级别顺序遍历将节点插入二叉树
- 尝试将节点插入链表中,但我需要一个重载运算符<函数
- 将节点插入二叉搜索树
- 尝试将节点插入矢量<node>,但程序在push_back时不断崩溃
- 将节点插入二进制搜索树/链表
- 将节点插入到不带头指针的排序列表中
- 错误:SList.cpp:(.text+0x69):尝试将节点插入链表头C++时未定义对"SLNode::SLNode()"的引用
- 为什么在尝试将新节点插入列表时出错
- 节点插入二进制树C++
- 为什么我不能将 head 之后的节点插入C++链表?