按照严版伪代码写线性表的顺序实现

# include <stdio.h>
# include <malloc.h>
# include <stdlib.h>

# define INIT_LIST_SIZE 10
# define LISTINCREMENT 5

typedef struct Node
{
	int data;
	char ch;
}* PNODE, NODE;

typedef struct List
{
	PNODE elem;
	int length;
	int listsize;
}* LINKLIST, LIST;

void init (LINKLIST &pL)
{
	pL->elem = (PNODE)malloc(sizeof(NODE) * INIT_LIST_SIZE);

	if (!pL->elem)
	{
		printf("内存分配失败!\n");

		exit(-1);
	}

	pL->listsize = INIT_LIST_SIZE;
	pL->length = 0;

	return;
}
void Delete (LINKLIST &pL, int pos)
{
	if (pos < 1 || pos > pL->length)
	{
		printf("输入的位置%d不合法!\n", pos);

		return;
	}

	PNODE p = pL->elem + pos - 1;
	PNODE q = pL->elem + pL->length -1;

	printf("删掉的元素内容:%d, %c\n", p->data, p->ch);

	for (p; p < q; p++)
	{
		p->data = (p + 1)->data;
		p->ch = (p + 1)->ch;
	}

	pL->length--;


	return;
}

void Insert (LINKLIST &pL, int pos, int val, char ch)
{
	if (pos < 1 || pos > pL->length + 1)
	{
		printf("输入的位置%d不合法!\n", pos);

		return;
	}

/*
	if (pL->length == pL->listsize)
	{
		pL->elem = (PNODE)realloc(sizeof(NODE) * (pL->listsize + LISTINCREMENT));	//realloc不会用啊,先放着

		if (!pL->elem)
		{
			printf("内存分配失败!\n");

			return;
		}
	}
*/

	PNODE p = pL->elem + (pos - 1);
	PNODE q = pL->elem + (pL->length - 1);

	for (q; q >= p; q--)
	{
		(q + 1)->data = q->data;
		(q + 1)->ch = q->ch;
	}

	p->data = val;
	p->ch = ch;

	pL->length++;

	printf("插入元素:%d, %c\n", val, ch);

	return;
}

void Locate(LINKLIST &pL, int val)	//定位data值为val的元素
{
	int change = 1;
	PNODE p = pL->elem;

	for (int i = 0; i < pL->length; i++)	//找出所有相符的
	{
		if (p[i].data == val)
		{
			printf("第%d个元素相符,内容为:%d, %c\n", i + 1, p[i].data, p[i].ch);

			change = 0;
		}
	}

	if (change)
	{
		printf("没有相符元素!\n");
	}

/*
	while (p->data != val && p++ <= (pL->elem + (pL->length - 1)));	//找出第一个相符的

	if (p > (pL->elem + (pL->length - 1)))
	{
		printf("没有相符元素!\n");
	}
	else
	{
		printf("找到的第一个相符元素在%d位置,内容为:%d, %c\n", p - pL->elem + 1, p->data, p->ch);
	}
*/


	return;
}

void Traverse(LINKLIST &pL)
{
	if (!pL->length)
	{
		printf("空线性表!\n");

		return;
	}

	for (int i = 0; i < pL->length; ++i)
	{
		printf("%d, %c\n", pL->elem[i].data, pL->elem[i].ch);
	}

	return;
}
int main(void)
{
	LIST L;
	LINKLIST pL = &L;
	init(pL);

	Insert(pL, 1, 1, 'z');
	Insert(pL, 2, 3, 'y');
	Insert(pL, 3, 5, 'x');
	Insert(pL, 4, 7, 'w');
	Insert(pL, 5, 7, 'v');
	Insert(pL, 6, 11, 'u');
	Insert(pL, 7, 13, 't');
	Insert(pL, 8, 15, 's');
	Insert(pL, 9, 17, 'r');
	Insert(pL, 10, 19, 'q');
	Traverse(pL);
	Insert(pL, 11, 333, 'p');
	Delete(pL, 3);
	Locate(pL, 7);
	Traverse(pL);

	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值