可变数组的缺陷
issues
Allocate new memory each time it inflates is an easy and clean way.But
It takes times to copy ,and may fail in memory restricted situation
Linked blocks
no copy
链表
//typedef struct _node{
//
// int value;
// struct _node *next ;
// }Node;
int main(int argc, char *argv []) {
Node * head = NULL;
int number;
do {
scanf("%d " ,&number);
if (number != -1 ){
//add to linked-list
Node *p = (Node*) malloc(sizeof(Node));
p->value = number;
p->next = NULL;
//find the last
Node *last = head;
if (last ){
while (last ->next ){
last = last ->next ;
}
//attach
last ->next = p;
}
else {
head = p;
}
}
}while (number != -1 );
return 0 ;
}
链表的函数
#include <stdio.h>
#include <stdlib.h>
#include "node.h"
typedef struct _list{
Node* head;
}List;
int main(int argc, char *argv[]) {
List list ;
int number;
list .head = NULL;
do {
scanf ("%d" ,&number);
if (number != -1 ){
add(&list ,number);
}
}while (number != -1 );
return 0 ;
}
void add(List* pList,int number){
Node *p = (Node*)malloc (sizeof (Node));
p->value = number;
p->next = NULL;
Node *last = pList->head;
if (last){
while (last->next){
last = last->next;
}
last->next = p;
}
else {
pList->head = p;
}
}