如何在不知道有多少个数字的情况下,往数组里输入数字?
1 回答
米脂
TA贡献1836条经验 获得超3个赞
请问你是用什么语言的?
如果是用java或者c# ,,那么使用List,或者Array类,都可以在不知道有多少数字的情况下push进去。
如果是C/C++,那么由于c/c++中 不允许定义动态数组 (C++中可以使用STL里的List),也就是数组初始化必须标明长度。这个时候就需要自己来实现一个可动态分配的数组。我用指针和结构体写了一个样例,其中 t指向的就是数组的首个地址,这样可以遍历,删除,增加数字。
struct node
{ int value;
node * next;
};int main()
{
int b;
node *last = new node;
last->next = new node;
node *start = last; //输入一串数字以-1为结束标志
while(true)
{
node *current = new node;
current->next = new node;
scanf("%d",&b); if(b==-1) break;
current->value = b;
last->next= current;
last = current;
}
//t 指向数组首个地址
node *t=start->next; //输出数字
while(t->next!=NULL)
{
printf("%d",t->value);
t=t->next;
}
}- 1 回答
- 0 关注
- 1461 浏览
添加回答
举报
0/150
提交
取消
