(p143)11.1-4大数组直接寻址

首先,直接访问的肯定是大数组,因此选择在大数组(h)里存元素在栈(st类似于栈)中的位置(如果有的话),注意h应该要是unsigned int类型的,不然有可能为负数,引起数组越界访问错误

/*
 * source.c
 *
 *  Created on: Feb 24, 2016
 *      Author: wing
 */
#include<stdio.h>
#include<stdlib.h>
#define maxn 100
#define maxsize 1000000
struct stack{
	int s[maxn];
	int top;
};
int insert(unsigned int *h,struct stack *st,int n)
{
	if (st->top==maxn-1)
	{
		printf("stack overflow!\n");
		return 0;
	}
	st->top++;
	h[n]=st->top;
	st->s[st->top]=n;
	return 0;
}
int search(unsigned int *h,struct stack *st,int n)
{
	if (n<=maxsize&&h[n]<=st->top&&st->s[h[n]]==n)
		return 1;
	else
		return 0;
}
int Delete(unsigned int *h,struct stack*st,int n)
{
	if (search(h,st,n))
	{
		st->s[h[n]]=st->s[st->top];
		h[st->s[st->top]]=h[n];
		st->top--;
		return 0;
	}
	else
		if (st->top==-1)
				{
					printf("stack underflow!\n");
					return 0;
				}
		else
		{
			printf("not found!\n");
			return 0;
		}
}
int main(void)
{
	int i,n;
	unsigned int h[maxsize+1];
	struct stack st;
	st.top=-1;
	scanf("%d",&i);
	while (i!=-1)
	{
		switch (i)
		{
		case 1:scanf("%d",&n);insert(h,&st,n);break;
		case 0:scanf("%d",&n);Delete(h,&st,n);break;
		case 2:scanf("%d",&n);printf("%d\n",search(h,&st,n));;break;
		default:break;
		}
		scanf("%d",&i);
	}
	return 0;
}


你可能感兴趣的:(编程,算法,算法导论)