請(qǐng)問(wèn)你是用什么語(yǔ)言的?
如果是用java或者c# ,,那么使用List,或者Array類,都可以在不知道有多少數(shù)字的情況下push進(jìn)去。
如果是C/C++,那么由于c/c++中 不允許定義動(dòng)態(tài)數(shù)組 (C++中可以使用STL里的List),也就是數(shù)組初始化必須標(biāo)明長(zhǎng)度。這個(gè)時(shí)候就需要自己來(lái)實(shí)現(xiàn)一個(gè)可動(dòng)態(tài)分配的數(shù)組。我用指針和結(jié)構(gòu)體寫了一個(gè)樣例,其中 t指向的就是數(shù)組的首個(gè)地址,這樣可以遍歷,刪除,增加數(shù)字。
struct node
{ int value;
node * next;
};int main()
{
int b;
node *last = new node;
last->next = new node;
node *start = last; //輸入一串?dāng)?shù)字以-1為結(jié)束標(biāo)志
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 指向數(shù)組首個(gè)地址
node *t=start->next; //輸出數(shù)字
while(t->next!=NULL)
{
printf("%d",t->value);
t=t->next;
}
}