如何在不知道有多少個數字的情況下,往數組里輸入數字?
如何在不知道有多少個數字的情況下,往數組里輸入數字?
慕桂英4014372
2018-08-14 11:14:45
TA貢獻1836條經驗 獲得超3個贊
請問你是用什么語言的?
如果是用java或者c# ,,那么使用List,或者Array類,都可以在不知道有多少數字的情況下push進去。
如果是C/C++,那么由于c/c++中 不允許定義動態數組 (C++中可以使用STL里的List),也就是數組初始化必須標明長度。這個時候就需要自己來實現一個可動態分配的數組。我用指針和結構體寫了一個樣例,其中 t指向的就是數組的首個地址,這樣可以遍歷,刪除,增加數字?!?/p>
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; } }
舉報