warning C4518: 'int ' : storage-class or type specifier(s) unexpected here; ignored
error C2146: syntax error : missing ';' before identifier 'BinarySearch'
fatal error C1004: unexpected end of file found
对于这样的语句:if (newbase == NULL)
NULL在C++中要定义么,怎么定义????????????
#include <iostream>
#include <stdlib.h>
#include <malloc.h>
using namespace std;
const int increment = 20;
//函数声明
int Compare(int a, int b)
int BinarySearch(int list[], int target, int n)
int InsertNewOne(int list[], int n, int target)
int main()
{
int a[16];
int i;
int location; //目标元素的位置
int Target; //目标元素
a[0] = 0;
//输入Target
cout<<endl<<"Please input the Target:";
cin>>Target;
cout<<endl;
//初始化a[]
for (i=1; i<16; i++)
{
a[i] = 2*i-1;
a[0]++;
}
location = BinarySearch(a, Target, a[0]);
//输出a[]的相关数据
cout<<endl<<"The elements of the list are:"<<endl;//输出A[]的数据
for (i=1; i<16; i++)
cout<<a[i];
cout<<endl<<"The length is:"<<a[0]<<endl;//输出长度
cout<<endl<<"The Target is:"<<Target<<endl;//输出要查找的元素
//输出查找到的元素位置,如果为0,则表明元素不存在
cout<<endl<<"The location is:"<<location<<endl;
if (location == 0)
//如果在Target不在线性表中,则将Target插入到线性表中
location = InsertNewOne (a, a[0], Location, Target);
return 0;
}
//Compare: 比较函数
//a和b为两个待比较元素
int Compare(int a, int b)
{
if (a < b)
return -1;
else
if (a == b)
return 0;
else // a>b
return 1;
}
//BinarySearch:二叉查找
//list:待查找的线性表
//target:目标元素
//n:list的长度
int BinarySearch(int list[], int target, int n)
{
int start=1;
int end=n;
int middle;
while (start <= end)
{
middle = (start + end) / 2;
switch (Compare(list[middle], target))
{
case -1 : start = middle+1;
break; //list[middle]<target
case 0 : return middle;
break; //list[middle]=target
case 1 : end = middle-1;
break; //list[middle]>target
default : break;
}//switch
}//while
return 0;
}//BinarySearch
//InsertNewOne:插入一个新的元素
//list:待插入的元素
//n:list的长度
//target:目标元素
int InsertNewOne(int list[], int n, int target)
{
int i;
int location;
int *newbase;//临时变量,用来存储新分配到的存储单元的地址
//list已满,再申请20个存储空间
if (n == 15)
{
newbase = (int *) realloc (list, (n + increment) * sizeof (int));
if (newbase == NULL)
exit -1;
else
list = newbase;
}
//找到适合的位置i
for (i=1; i<16; i++)
if ((target>list[i]) && (target<list[i+1]))
location = i;
//移动list[i]以后的元素并插入target
for (i=n; i>0; i++)
list[i] = list[i+1];
//完成赋值
list[location] = target;
return 0;
}