Position BinarySearch( List L, ElementType X )
{
Position l = 1, r = L->Last, mid;
while (r - l >= 0)
{
mid = (l + r) / 2;
if (L->Data[mid] > X) // 中间位置的数大于要查找的数,那么在中间数的左区间找
r = mid - 1;
else if (L->Data[mid] == X) //中间位置的数等于要查找的数
return mid;
else // 中间位置的数小于要查找的数,那么在中间数的右区间找
l = mid + 1;
}
return NotFound;
}
习题1.9 有序数组的插入
bool Insert( List L, ElementType X ){
if(L->Last==MAXSIZE-1) //表中没有空位
return false;
for (int i=0; i<=L->Last; i++) {
if(L->Data[i]==X) //x已经在Data[]中了
return false;
else if (L->Data[i]<X) { //插入的没到X
for (int j=L->Last; j>=i; j--) //找到i的位置
L->Data[j+1]=L->Data[j];
L->Data[i]=X;
L->Last=L->Last+1;
return true;
}
else if(i==L->Last&&L->Data[i]>X){
L->Data[L->Last+1]=X;
L->Last=L->Last+1;
return true;
break;
}
}
}
习题2.4 递增的整数序列链表的插入
List Insert(List L, ElementType X)
{
List head = L;
List t = head;
while(t -> Next != NULL && t -> Next -> Data <= X) //遍历t
t = t -> Next;
List q;
q = (struct Node *)malloc(sizeof(struct Node *));
q -> Data = X;
q -> Next = t -> Next;
t -> Next = q;
return head;
}
double dist(double h, double p)
{
double high = h;
double time = p;
double mix = time * h;
while (mix>TOL)
{
high =high +2*mix;
mix=p*mix;
}
return high;
}
习题3.3 线性表元素的区间删除
List Delete(List L, ElementType minD, ElementType maxD) {
Position i;
Position* a = (Position *)malloc((L->Last + 1) * sizeof(Position));
Position front = 0, rear = 0;
Position max = L->Last;
for (i = 0; i <= max; i++) {
if (L->Data[i] > minD&&L->Data[i] < maxD) {
a[rear++] = i;
L->Last--;
}
else {
a[rear++] = i;
L->Data[a[front++]] = L->Data[i];
}
}
return L;
}
习题3.5 求链表的倒数第m个元素
ElementType Find(List L, int m) {
List p = L;
List q = L;
int len = 0;
while (p->Next != NULL) {
if (len != m) {
p = p->Next;
len++;
}
else {
p = p->Next;
q = q->Next;
}
}
if (len == 0)
return ERROR;
return q->Next->Data;
}
习题1.8 二分查找Position BinarySearch( List L, ElementType X ){ Position l = 1, r = L->Last, mid; while (r - l >= 0) { mid = (l + r) / 2; if (L->Data[mid] > X) // 中间位置的数大于要查找的数,那么在中间数的左区间找 r = mid - 1