.可变数组存在的问题:
.每次内存不够用都要花时间赋值前一段空间的内容
.可能会遇到空间不够的情况
.解决方案
.不用复制,直接告诉下一块内存的位置,链接起来就能充分利用内存空间
.制作一个单向链表[licked-list.c]
.node2.h
#ifndef __NODE_H__
#define __NODE_H__
typedef struct _node
{
int value;
struct _node* next;
}Node;
typedef struct _list
{
Node* head;
} List;
void add(List* list, int number);
void print(List* list);
int search(List* list, int number);
void remove_(List* list, int number);
void delete_linked_list(List* pList);
#endif
.function.c
#include <stdio.h>
#include <stdlib.h>
#include "node2.h"
//delete linked-list
void delete_linked_list(List* pList)
{
Node* p;
Node* q = NULL;
for( p=pList->head; p;p=q->next )
{
q = p->next;
free(p);
}
}
//remove a number of linked-list
void remove_(List* pList, int number)
{
//Find a number and remove it from linked-list
Node* p;
Node* q;
for( q=NULL, p=pList->head; p; q=p,p=p->next)
{
if( p->value == number )
{
if( q )
{
q->next = p->next;
free(p);
}else{
pList->head = p->next;
}
}
}
}
void add(List* list, int number)
{
//add to link_list
Node* p = (Node*)malloc(sizeof(Node));
p->value = number;
p->next = NULL;
//find the last
Node* last = list->head;
if( last )
{
while( last->next )
{
last = last->next;
}
//attach
last->next = p;
}
else
{
list->head = p;
}
}
//print linked-list
void print(List* pList)
{
//iterate through linked-list
Node* p;
for( p=pList->head; p; p=p->next )
{
printf("%d\t", p->value);
}
printf("\n");
}
//search number of linked-list
int search(List* pList ,int number)
{
int isFound = 0;
int result = -1;
Node* p;
for( p=pList->head; p; p=p->next )
{
if( p->value == number )
{
printf("Found number is %d\n", number);
isFound = 1;
break;
}
}
if( isFound )
result = number;
return result;
}
.link-list2.c
#include <stdio.h>
#include <stdlib.h>
#include "node2.h"
/*
typedef struct _node{
int value;
struct _node* next;
}Node;
*/
int main(int argc, char const *argv[])
{
List list;
list.head = NULL;
int number;
do{
scanf("%d", &number);
if( number != -1 )
{
add(&list, number);
}
}while( number != -1 );
print(&list);
delete_linked_list(&list);
/*
int goal;
scanf("%d", &goal);
remove_(&list, goal);
print(&list);
*/
/* int goal;
scanf("%d", &goal);
if( search(&list, goal) != -1 )
{
printf("Success!\n");
}else{
printf("Unsuccess!\n");
}
*/
return 0;
}
.运行结果: