1. 程式人生 > >資料結構與演算法(七)

資料結構與演算法(七)

模組一:線性結構(所有的節點可以用一根線穿起來,首節點前沒有節點,尾節點後沒有節點,中間節點前後只有一個節點)
連續儲存(陣列)
離散儲存(連結串列)
線性結構的兩種常見應用之一:棧
線性結構的兩種常用應用之一:佇列
動態陣列的構建和操作(添插刪序)

#include <stdio.h>
#include<malloc.h>//包含malloc函式
#include<stdlib.h>//包含了exit函式

struct Array
{
	int len;//陣列的長度
	int * a;//陣列的首單元的地址
	int cnt;//當前陣列的有效長度
};

void init_arr(struct Array *p,int len)
{
	p->len = 10;
	p->cnt = 0;
	p->a = (int *)malloc(sizeof(int)*len);
	if(p->a == NULL)
	{
		printf("動態記憶體分配失敗!\n");
		exit(-1);
	}
}

bool is_full(struct Array *p)
{
	if(p->cnt == p->len)
		return true;
	else
		return false;
}

bool is_empty(struct Array *p)
{
	if(p->cnt == 0)
		return true;
	else
		return false;
}

bool append(struct Array *p,int x)
{
	int i;
	if (is_full(p))
		return false;
	else
	{
			i = p->cnt;
			p->a[i] = x;
	}
		p->cnt++;
	return true;
}

bool insert(struct Array *p,int pos,int x)//pos是插入的位置,從1開始,在pos的前面插入
{
	if (pos<1||pos>p->cnt+1)
		return false;
	else
	{
		int i;
		for(i=p->cnt-1;i>=pos-1;--i)
		{
			p->a[i+1] = p->a[i];
		}
		p->a[pos-1] = x;
	}
	p->cnt++;
	return true;
}

void show_arr(struct Array *p)
{
	if (is_empty(p))
		printf("陣列為空!\n");
	else
		for(int i = 0;i<p->cnt;++i)
		{
			printf("%d ",p->a[i]);
		}
	printf("\n");
}

void invert_arr(struct Array *p)
{
	int t;
	int i = 0;
	int j = p->cnt-1;
	while(i<j)
	{
		t = p->a[i];
		p->a[i] = p->a[j];
		p->a[j] = t;
		i++;
		j--;
	}
}

sort_arr(struct Array *p)
{
	int t;
	for(int i = 0;i<p->cnt-1;i++)
		for(int j = i+1;j<p->cnt;j++)
			if(p->a[i]>p->a[j])
			{
				t = p->a[i];
				p->a[i] = p->a[j];
				p->a[j] = t;
			}
}

bool del_arr(struct Array *p,int pos,int *del_val)
{
	if(is_empty(p))
	{
		printf("陣列為空!");
		return false;
	}

	if (pos<1||pos>p->cnt+1)
		return false;
	
	*del_val = p->a[pos-1];
	for(int i=pos;i<=p->cnt-1;i++)
	{
			p->a[i-1] = p->a[i];
	}
	
	
	p->cnt--;
	return true;
}
int main(void)
{
	struct Array a;
	int len = 10;
	int del_val;
	init_arr(&a,len);
	append(&a,2);
	append(&a,5);
	append(&a,3);
	append(&a,8);
	append(&a,6);
	append(&a,1);
	show_arr(&a);
	insert(&a,2,9);
	show_arr(&a);
	del_arr(&a,4,&del_val);
	show_arr(&a);
	printf("刪除的元素是: %d\n",del_val);
	invert_arr(&a);
	show_arr(&a);
	sort_arr(&a);`在這裡插入程式碼片`
	show_arr(&a);
	return 0;
}