数据结构c++代码实现

顺序表

#include<iostream>
#include<string>

using namespace std;

//#define MAX_SIZE 100
//
//typedef struct 
//{
//	int *elems;		//顺序表的基地址
//	int length;		//长度
//	int size;		//总空间大小
//}SqList;

template <typename T>
class SqList
{
public:
	SqList() {}
	SqList(int size) {
		m_size = size;
		elems = new T[size];
		m_length = 0;
	}
	int length()//获取长度
	{
		return m_length;
	}
	int size()//获取容量
	{
		return m_size;
	}
	void PushBack(T x)//尾插数据
	{
		if (m_length != m_size)
		{
			elems[m_length] = x;
			m_length++;
		}
	}
	T& operator [](int x)//重载[],使可以访问赋值
	{
		if (x >= m_length)
		{
			throw - 1;
		}
		else
		{
			return elems[x];
		}
	}
	void Insert(int num,T x)//插入数据
	{
		if (num >= m_length)
		{
			throw - 1;
		}
		else
		{			
			m_length++;
			for (int i = m_length - 1; i > num; i--)
			{
				elems[i] = elems[i - 1];
			}
			elems[num] = x;
		}
	}
	void Delete(int x)//删除数据
	{
		if (m_length == x)
		{
			m_length--;
		}
		else
		{
			for (int i = x; i < m_length - 1;i++)
			{
				elems[i] = elems[i + 1];
			}
			m_length--;
		}
	}
	void destroyList()//销毁顺序表
	{
		delete[]elems;
		m_length = 0;
		m_size = 0;
	}
	~SqList()
	{
		delete[]elems;
	}
private:
	T *elems;		//顺序表的基地址
	int m_length;	//长度
	int m_size;		//总空间大小
};

int main()
{
	SqList<string> s(20);
	s.PushBack("x");
	s.PushBack("y");
	s.PushBack("z");
	cout << s.length() << " " << s[0] << " " << s.size() << endl;
	s.Insert(1, "a");
	cout << s[0] << " " << s[1] << " " << s[2] << " " << s[3] << endl;
	s.Delete(1);
	for (int i = 0; i < s.length(); i++)
	{
		cout << s[i] << " ";
	}
	cout << endl;

	system("pause");
	return 0;
}

链表

#include<iostream>

using namespace std;

typedef struct _LinkNode {
	int data;	//节点的数据域
	struct _LinkNode *next;	//节点的指针域
}LinkNode,LinkList;//LinkNode为指向结构体的指针类型

//初始化
bool InitList(LinkList* &L)
{
	L = new LinkNode;
	if (!L)return false;
	L->next = NULL;
	return true;
}
//前插法
bool Push_font(LinkList* &L,LinkNode *node)
{
	if (!L || !node)return false;

	node->next = L->next;
	L->next = node;
	return true;
}
//尾插法
bool Push_back(LinkList* &L, LinkNode *node)
{
	if (!L || !node)return false;

	LinkList * last = NULL;
	last = L->next;
	while (last->next)
	{
		last = last->next;
	}
	last->next = node;
	node->next = NULL;
	return true;
}
//任意位置插入
bool ListInsert(LinkList* &L,int i,int &e)
{
	if (!L)return false;

	int j = 0;
	LinkList *p = L;
	
	while (p && j != i - 1)//查找第i-1个节点,使p指向该节点
	{
		p = p->next;
		j++;
	}
	if (!p || j > i - 1)
	{
		return false;
	}
	//生成新的节点
	LinkList *s = new LinkNode;
	s->data = e;
	s->next = p->next;
	p->next = s;
	return true;
}
//打印
void ListPrint(LinkList* &L)
{
	LinkList * p = NULL;
	if (!L) 
	{
		cout << "链表为空!" << endl;
		return;
	}
	p = L->next;

	while (p) 
	{
		cout << p->data << "\t";
		p = p->next;
	}
	cout << endl;
}

//取出位置i的元素
bool Limk_GetEliem(LinkList* &L,int i,int &e)
{
	if (!L || !L->next)return false;

	int j = 1;
	LinkList *p = L->next;

	while (p && j < i)
	{
		p = p->next;
		j++;
	}
	if (!p || j > i)
	{
		return false;
	}
	e = p->data;
	return true;
}
//查找元素
bool LinkFind(LinkList* &L, int e)
{
	if (!L)return false;

	LinkList*p;

	p = L->next;
	while (p&&p->data != e)
	{
		p = p->next;
	}

	if (!p)return false;

	return true;
}
//删除元素
bool  LinkDelete(LinkList*&L, int i)
{
	if (!L)return false;

	int j = 0;
	LinkList *p = L;

	while (p && j < i-1)
	{
		p = p->next;
		j++;
	}
	if (!(p->next) || (j > i - 1)) 
	{
		return false;
	}
	LinkList *s;
	s = p->next;
	p->next = s->next;
	delete s;
	return true;
}
//单链表销毁
void LinkDestroy(LinkList* &L)
{
	LinkList *p = L;
	cout << "销毁链表!" << endl;
	while (p)
	{
		L = L->next;//L指向下一个节点
		delete p;//删除当前节点
		p = L;
	}
}




int main()
{
	LinkList *L = NULL;
	LinkList *s = NULL;
	//初始化
	InitList(L);
	//头插法插入
	int n = 0;
	cout << "请输入要插入的元素个数:" << endl;
	cin >> n;
	cout << "请依次输入"<< n <<"个元素:" << endl;
	while (n > 0)
	{
		s = new LinkNode;	//生成新的节点s
		cin >> s->data;
		Push_font(L, s);
		n--;
	}
	//打印
	ListPrint(L);
	cout << "---------------------" << endl;

	//尾插法插入
	cout << "请输入要插入的元素个数:" << endl;
	cin >> n;
	cout << "请依次输入" << n << "个元素:" << endl;
	while (n > 0)
	{
		s = new LinkNode;	//生成新的节点s
		cin >> s->data;
		Push_back(L, s);
		n--;
	}
	//打印
	ListPrint(L);
	
	//任意位置插入
	int x = 0;
	cout << "请输入要插入的位置:" << endl;
	cin >> n;
	cout << "请输入元素:" << endl;
	cin >> x;
	ListInsert(L, n, x);
	ListPrint(L);

	//取出元素
	cout << "请输入要取出第几位元素:" << endl;
	cin >> n;
	int a = 0;
	Limk_GetEliem(L, n, a);
	cout << "取出的第" << n << "位元素为:" << a << endl;

	//删除元素
	cout << "请输入要删除第几个元素:" << endl;
	cin >> n;
	LinkDelete(L, n);
	ListPrint(L);

	//销毁链表
	LinkDestroy(L);


	system("pause");
	return 0;
}

#include<iostream>

using namespace std;

#define MaxSize 128

typedef int ElemType;

typedef struct _SqStack
{
	ElemType *base;		//栈底指针
	ElemType *top;		//栈顶指针
}SqStack;

//初始化
bool InitStack(SqStack &S)//构造一个空栈
{
	S.base = new ElemType[MaxSize];//分配最大容量为MaxSize的空间
	if (!S.base)//分配失败
	{
		return false;
	}
	S.top = S.base;//top和base指向同一块地址,空栈
	return true;
}

//入栈
bool PushStack(SqStack &S, ElemType e)
{
	if (S.top - S.base == MaxSize)//栈满
	{
		return false;
	}
	*(S.top++) = e;	//元素e压入栈顶,然后栈顶指针+1

	return true;
}

//出栈
bool PopStack(SqStack &S, ElemType &e)
{
	if (S.top == S.base)//栈空
	{
		return false;
	}

	e = *(--S.top);	//栈顶指针-1,将栈顶元素给e

	return true;
}

//获取栈顶元素
ElemType GetTop(SqStack &S)
{
	if (S.top != S.base)//栈非空
	{
		return *(S.top - 1);
	}
	else
	{
		return -1;
	}
}

//判断栈是否为空
bool IsEmpty(SqStack &S)
{
	if (S.top == S.base)
	{
		return true;
	}
	else
	{
		return false;
	}
}

//栈中元素个数
int GetSize(SqStack &S)
{
	return (S.top - S.base);
}

//清空栈
void DestoryStack(SqStack &S)
{
	if (S.base)
	{
		free(S.base);
		S.base = NULL;
		S.top = NULL;
	}
}


int main()
{
	SqStack S;
	InitStack(S);
	int n, temp;
	cout << "请输入要入栈元素的个数:" << endl;
	cin >> n;
	for (int i = 0; i < n; i++)
	{
		cout << "请输入第" << i + 1 << "个元素:";
		cin >> temp;
		PushStack(S, temp);
	}

	ElemType e = GetTop(S);
	cout << "栈顶元素为:" << e << endl;

	cout << "当前栈中元素有:" << GetSize(S) << endl;

	for (int i = 0; i < n; i++)
	{
		cout << "第" << i + 1 << "个出栈元素为:";
		PopStack(S, temp);
		cout << temp << endl;
	}

	DestoryStack(S);

	system("pause");
	return 0;
}

队列

#include <iostream>
using namespace std;

//队列先进先出
#define MaxSize 5	//最大容量
typedef int DataType;	//队列中元素类型

typedef struct Queue
{
	DataType queue[MaxSize];
	int front;		//队头指针
	int rear;		//队尾指针
}SeqQueue;

//队列初始化
void InitQueue(SeqQueue *SQ)
{
	if (!SQ)return;
	SQ->front = SQ->rear = 0;//队头队尾同时置0
}
//判断队列是否为空
int IsEmpty(SeqQueue *SQ)
{
	if (!SQ)return 0;
	if (SQ->front == SQ->rear)
	{
		return 1;
	}
	return 0;
}
//判断队列是否为满
int IsFull(SeqQueue *SQ)
{
	if (!SQ)return 0;
	if (SQ->rear == MaxSize)
	{
		return 1;
	}
	return 0;
}

//元素入队
int EnterQueue(SeqQueue *SQ,DataType data)
{
	if (!SQ)return 0;
	if (IsFull(SQ)) 
	{
		cout << "无法插入元素" << data << " 队列已满!" << endl;
		return 0;
	}
	SQ->queue[SQ->rear] = data;//在队尾插入元素data
	SQ->rear++;//队尾指针后移一位
	return 1;
}
//出队 
int DeleteQueue(SeqQueue *SQ,DataType *data)
{
	if (!SQ||IsEmpty(SQ))return 0;
	if (!data)return 0;
	*data = SQ->queue[SQ->front];
	for (int i = 0; i < SQ->rear; i++)
	{
		SQ->queue[i] = SQ->queue[i + 1];
	}
	SQ->rear --;
	return 1;
}

//打印
void PrintQueue(SeqQueue *SQ)
{
	if (!SQ)return;
	int i = SQ->front;
	while (i < SQ->rear)
	{
		cout << " " << SQ->queue[i];
		i++;
	}
	cout << endl;
}
//获取队首元素,不出队
int GetHead(SeqQueue *SQ, DataType* data)
{
	if (!SQ || IsEmpty(SQ))
	{
		cout << "队列为空!" << endl;
	}
	return *data = SQ->queue[SQ->front];
}
//清空队列
void ClearQueue(SeqQueue *SQ)
{
	if (!SQ)return;
	SQ->front = SQ->rear = 0;
}
//获取队列长度
int GetLength(SeqQueue *SQ)
{
	if (!SQ)return 0;
	return SQ->rear - SQ->front;
}



int main()
{
	SeqQueue *SQ = new SeqQueue;
	DataType data;

	//初始化队列
	InitQueue(SQ);

	//入队
	for (int i = 0; i < 7; i++)
	{
		EnterQueue(SQ, i);
	}
	//打印
	cout << "队列中元素:";
	PrintQueue(SQ);

	//出队
	DeleteQueue(SQ, &data);
	cout << "出队元素:" << data << endl;
	cout << "队列中元素:";
	PrintQueue(SQ);

	//获取首元素
	GetHead(SQ, &data);
	cout << "队首元素:" << data << endl;

	//长度
	int length = GetLength(SQ);
	cout << "队列长度为:" << length << endl;

	//清空队列
	ClearQueue(SQ);

	system("pause");
	return 0;
}

#include <iostream>

using namespace std;

#define DEFAULT_CAPCITY 128

typedef struct _Heap {
	int *arr;		//存储堆元素的数组
	int size;		//当前已存储的元素个数
	int capacity;	//当前存储的容量
}Heap;

bool initHeap(Heap &heap, int *orginal, int size);
bool insert(Heap &heap, int  value);//尾部插入节点
static void buildHeap(Heap &heap);
static void adjustDown(Heap &heap, int index);//向下调整
static void adjustUp(Heap &heap, int index);//向上调整
bool popMax(Heap &heap,int &value);//出堆

//初始化堆
bool initHeap(Heap &heap, int *orginal, int size)
{
	int capacity = DEFAULT_CAPCITY > size ? DEFAULT_CAPCITY : size;

	heap.arr = new int[capacity];
	if (!heap.arr)return false;

	heap.capacity = capacity;
	heap.size = 0;

	if (size > 0) {
		//内存copy    新地址,原地址,内存空间
		memcpy(heap.arr, orginal, size * sizeof(int));
		heap.size = size;
		//建堆
		buildHeap(heap);
	}
	return true;
}

/*从最后一个父节点(size/2-1的位置)逐个往前调整所有父节点(直到根节点),
确保每一个父节点都是一个最大堆,最后整体上形成一个最大堆*/
void buildHeap(Heap &heap)
{
	int i;
	for (i = heap.size / 2 - 1; i >= 0; i--)
	{
		adjustDown(heap, i);
	}
}

//将当前节点和子节点调整成最大堆,向下调整
void adjustDown(Heap &heap, int index)
{
	int cur = heap.arr[index];//当前待调整的节点
	int parent, child;

	/*判断是否存在大于当前节点的子节点,如果不存在,则堆本身是平衡的,不需要调整;
	如果存在,则将最大的子节点于之交换,交换后,如果这个子节点还有子节点,则要继续
	按照同样的步骤堆这个子节点进行调整
	*/
	for (parent = index; (parent * 2 + 1) < heap.size; parent = child)
	{
		child = parent * 2 + 1;

		//取两个子节点中最大的节点
		if (((child + 1) < heap.size) && (heap.arr[child] < heap.arr[child + 1]))
		{
			child++;
		}

		//判断最大的节点是否大于当前的父节点
		if (cur >= heap.arr[child])//不大于,则不需要调整,跳出循环
		{
			break;
		}
		else
		{
			heap.arr[parent] = heap.arr[child];
			heap.arr[child] = cur;
		}

	}


}
//向上调整
void adjustUp(Heap &heap, int index)
{
	if (index < 0 || index >= heap.size)//大于堆的最大值直接return
	{
		return;
	}
	while (index > 0)
	{
		int temp = heap.arr[index];
		int parent = (index - 1) / 2;

		if (parent >= 0)
		{
			if (temp > heap.arr[parent])
			{
				//子节点的值大于父节点则交换两个值,并且把下标重新定义到父节点,一直向上操作
				heap.arr[index] = heap.arr[parent];
				heap.arr[parent] = temp;
				index = parent;
			}
			else//如果比父节点小就结束循环
			{
				break;
			}
		}
		else//越界结束循环
		{
			break;
		}
	}
}

/*最大堆尾部插入节点,同时保持最大堆特性*/
bool insert(Heap &heap, int  value)
{
	if (heap.size == heap.capacity)
	{
		fprintf(stderr, "栈空间耗尽!\n");
		return false;
	}
	
	int index = heap.size;
	heap.arr[heap.size++] = value;
	//向上调整
	adjustUp(heap, index);
	return true;
}

//出堆
bool popMax(Heap &heap,int &value)
{
	if (heap.size < 1)
	{
		return false;
	}
	value = heap.arr[0];
	heap.arr[0] = heap.arr[--heap.size];
	adjustDown(heap, 0);//向下调整
	return true;
}




int main()
{
	Heap hp;
	int origVals[] = { 1,2,3,87,93,82,92,86,95 };
	initHeap(hp, origVals, 9);
	insert(hp, 100);

	for (int i = 0; i < hp.size; i++)
	{
		cout << hp.arr[i] << " ";
	}
	cout << endl;

	cout << "最大元素依次出堆:" << endl;
	int max = 0;
	while (popMax(hp, max))
	{
		cout << max << " ";
	}
	cout << endl;
	system("pause");
	return 0;
}

二叉树

#include<iostream>

using namespace std;


#define MAX_NODE 1024

#define isLess(a, b) (a<b)

#define isEqual(a, b) (a==b)

typedef int ElemType;

typedef struct _Bnode
{
	ElemType data;			 //元素类型 
	struct _Bnode *lchild, *rchild;		//指向左右孩子节点
}Bnode, Btree;

//插入
bool InserBtree(Btree **root, Bnode *node)
{
	Bnode *tmp = NULL;
	Bnode *parent = NULL;

	if (!node)
	{
		return false;
	}
	else
	{
		//清空新节点的左右子树
		node->lchild = NULL;
		node->rchild = NULL;
	}

	if (*root)//存在根节点
	{
		tmp = *root;
	}
	else//不存在根节点
	{
		*root = node;
		return true;
	}

	while (tmp != NULL)
	{
		parent = tmp;//保存父节点

		if (isLess(node->data, tmp->data))
		{
			tmp = tmp->lchild;
		}
		else
		{
			tmp = tmp->rchild;
		}

	}

	if (isLess(node->data, parent->data))//找到空位置,进行插入
	{
		parent->lchild = node;
	}
	else
	{
		parent->rchild = node;
	}
	return true;
}

//查找最大节点
int findMax(Btree*root)
{
	if (root->rchild == NULL)
	{
		return root->data;
	}
	return findMax(root->rchild);
}

//删除
Btree* DeleteNode(Btree*root, int key)
{
	if (root == NULL)return NULL;

	//找到需要删除的节点
	if (root->data > key)
	{
		root->lchild = DeleteNode(root->lchild, key);
		return root;
	}
	if (root->data < key)
	{
		root->rchild = DeleteNode(root->rchild, key);
		return root;
	}

	//删除节点不存在左右子节点,即为叶子节点,直接删除
	if (root->lchild == NULL && root->rchild == NULL)return NULL;

	//删除节点存在右子节点,直接用右字节点取代删除节点
	if (root->lchild == NULL && root->rchild != NULL)return root->rchild;

	//删除节点存在左子节点,直接用左字节点取代删除节点
	if (root->lchild != NULL && root->rchild == NULL)return root->lchild;

	//删除节点存在左右子节点,直接用左子节点最大值取代删除节点
	int val = findMax(root->lchild);
	root->data = val;
	root->lchild = DeleteNode(root->lchild, val);
	return root;
}

//递归查找节点
Bnode* queryByRec(Btree *root, ElemType e)
{
	if (root == NULL || isEqual(root->data, e))
	{
		return root;
	}
	else if (isLess(e,root->data))
	{
		return queryByRec(root->lchild, e);
	}
	else
	{
		return queryByRec(root->rchild, e);
	}
}

//前序遍历递归实现,先遍历左子树再右子树
void preOrderRec(Btree *root)
{
	if (root == NULL)
	{
		return;
	}
	printf("- %d ", root->data);
	preOrderRec(root->lchild);
	preOrderRec(root->rchild);
}





int main()
{
	int test[] = { 19,7,25,5,11,15,21,61 };
	Bnode*root = NULL, *node = NULL;

	node = new Bnode;
	node->data = test[0];
	InserBtree(&root, node);

	for (int i = 1; i < sizeof(test) / sizeof(test[0]); i++)
	{
		node = new Bnode;
		node->data = test[i];
		if (InserBtree(&root, node))
		{
			printf("节点 %d 插入成功\n", node->data);
		}
		else
		{
			printf("节点 %d 插入失败\n", node->data);
		}
	}

	printf("前序遍历:");
	preOrderRec(root);
	cout << endl;

	DeleteNode(root, 21);

	printf("删除后,前序遍历:");
	preOrderRec(root);
	cout << endl;

	Bnode * node1 = queryByRec(root, 20);
	printf ("搜索二叉树,节点20%s\n", node1 ? "存在" : "不存在" );

	system("pause");
	return 0;
}

哈希表

#include<iostream>

using namespace std;

#define DEFAULT_SIZE 16

typedef struct _ListNode
{
	struct _ListNode *next;		//链表实现,指向下一个节点
	int key;		//索引
	void *data;		//数据
}ListNode;

typedef ListNode*List;
typedef ListNode*Element;

typedef struct _HashTable	//哈希表
{
	int TableSize;		//大小
	List *Thelists;
}HashTable;


//根据key计算索引,定位Hash桶的位置
int Hash(int key, int TableSize)
{
	return(key%TableSize);
}

//初始化哈希表
HashTable *InitHash(int TableSize)
{
	int i = 0;
	HashTable *hTable = NULL;
	
	if (TableSize <= 0)
	{
		TableSize = DEFAULT_SIZE;
	}

	//堆区申请内存
	hTable = (HashTable *)malloc(sizeof(HashTable));
	if (NULL == hTable)
	{
		printf("HashTable malloc error.\n");
		return NULL;
	}

	hTable->TableSize = TableSize;

	//为Hash桶分配内存空间,其为一个指针数组
	hTable->Thelists = (List *)malloc(sizeof(List)*TableSize);
	if (NULL == hTable->Thelists)
	{
		printf("HashTable malloc error.\n");
		free(hTable);
		return NULL;
	}

	//为Hash桶对应的指针数组初始化链表节点
	for (i = 0; i < TableSize; i++)
	{
		//动态分配空间
		hTable->Thelists[i] = (ListNode *)malloc(sizeof(ListNode));
		if (NULL == hTable->Thelists[i])
		{
			printf("HashTable malloc error.\n");
			free(hTable->Thelists);
			free(hTable);
			return NULL;
		}
		else
		{
			//数据全部设为0
			memset(hTable->Thelists[i], 0, sizeof(ListNode));
		}
	}

	return hTable;
}

//从哈希表中根据键值查找元素
Element Find(HashTable *HashTable, int key)
{
	int i = 0;
	List L = NULL;
	Element e = NULL;
	//得到哈希桶的下标
	i = Hash(key, HashTable->TableSize);
	//头节点
	L = HashTable->Thelists[i];
	e = L->next;
	//从0开始查找键值等于key的元素
	while (e != NULL && e->key != key)
	{
		e = e->next;
	}
	return e;
}

//哈希表插入元素,元素为键值对
void Insert(HashTable *HashTable, int key, void *value)
{
	Element e = NULL, tmp = NULL;
	List L = NULL;
	e = Find(HashTable, key);

	if (NULL == e)
	{
		tmp = (Element)malloc(sizeof(ListNode));;
		if (NULL == tmp)
		{
			printf("malloc error\n");
			return;
		}
		L = HashTable->Thelists[Hash(key, HashTable->TableSize)];//前插法
		tmp->data = value;
		tmp->key = key;
		tmp->next = L->next;
		L->next = tmp;
	}
	else
	{
		printf("the key already exist\n");
	}

}

//哈希表删除元素,元素为键值对
void Delete(HashTable *HashTable, int key)
{
	Element e = NULL, last = NULL;
	List L = NULL;
	int i = Hash(key, HashTable->TableSize);
	L = HashTable->Thelists[i];

	last = L;
	e = L->next;
	while (e != NULL && e->key != key)
	{
		//last记录删除节点的前一个节点
		last = e;
		e = e->next;
	}

	if (e)//如果键值存在
	{
		last->next = e->next;
		free(e);
	}
}

//哈希表元素中提取数据
void *Retrieve(Element e)
{
	return e ? e->data : NULL;
}

//销毁哈希表
void Destory(HashTable *HashTable)
{
	int i = 0;
	List L = NULL;
	Element cur = NULL, next = NULL;
	for (i = 0; i < HashTable->TableSize; i++)
	{
		L = HashTable->Thelists[i];
		cur = L->next;
		while (cur != NULL)
		{
			next = cur->next;
			free(cur);
			cur = next;
		}
		free(L);
	}
	free(HashTable->Thelists);
	free(HashTable);
}


int main()
{
	char *elems[] = { "小王","小李","小帅" };
	int i = 0;

	HashTable *HashTable = NULL;
	HashTable = InitHash(31);
	Insert(HashTable, 1, elems[0]);
	Insert(HashTable, 2, elems[1]);
	Insert(HashTable, 3, elems[2]);
	Delete(HashTable, 1);

	for (i = 0; i < 4; i++)
	{
		Element e = Find(HashTable, i);
		if (e)
		{
			printf("%s\n", (const char *)Retrieve(e));
		}
		else
		{
			printf("Not found [key:%d]\n", i);
		}
	}

	Destory(HashTable);

	system("pause");
	return 0;
}

#include<iostream>
#include<queue>

using namespace std;

#define Maxize 1024

typedef struct _EdgeNode	//与节点连接的边的定义
{
	int adjvex;		//邻接的顶点
	int weight;		//权重
	struct _EdgeNode *next;		//下一条变
}EdgeNode;

typedef struct _VertexNode	//顶点节点
{
	char data;		//节点数据
	struct _EdgeNode *first;	//指向邻接第一条边
}VertexNode,AdjList;

typedef struct _AdjListGraph	//图
{
	AdjList *adjlist;
	int vex;	//顶点数
	int edge;	//变数
}AdjListGraph;

bool visited[Maxize];	//全局数组,记录节点是否已被访问

int Location(AdjListGraph &G,char c);

//图的初始化
void Init(AdjListGraph &G)
{
	G.adjlist = new AdjList[Maxize];
	G.edge = 0;
	G.vex = 0;
	for (int i = 0; i < Maxize; i++)
	{
		visited[i] = false;
	}
}

//图的创建
void Create(AdjListGraph &G)
{
	cout << "请输入改图的顶点数以及边数:" << endl;
	cin >> G.vex >> G.edge;
	cout << "请输入相关顶点:" << endl;
	for (int i = 0; i < G.vex; i++)
	{
		cin >> G.adjlist[i].data;
		G.adjlist[i].first = NULL;
	}

	char v1 = 0, v2 = 0;//保存输入的顶点字符
	int i1, i2;			//保存顶点再数组中的下标

	cout << "请输入相关联边的顶点:" << endl;
	for (int i = 0; i < G.edge; i++)
	{
		cin >> v1 >> v2;
		i1 = Location(G, v1);
		i2 = Location(G, v2);

		if (i1 != -1 && i2 != -1)//寻找到位置
		{
			EdgeNode *temp = new EdgeNode;
			temp->adjvex = i2;
			temp->next = G.adjlist[i1].first;
			G.adjlist[i1].first = temp;
		}
	}

}

//通过顶点对应的字符寻找顶点在图中的邻节点
int Location(AdjListGraph &G, char c)
{
	for (int i = 0; i < G.edge; i++)
	{
		if (G.adjlist[i].data == c)
		{
			return i;
		}
	}
	return -1;
}

//对图上的顶点进行深度遍历
void DFS(AdjListGraph &G, int v)
{
	int next = -1;

	if (visited[v])return;

	cout << G.adjlist[v].data << " ";
	visited[v] = true;

	EdgeNode *temp = G.adjlist[v].first;

	while (temp)
	{
		next = temp->adjvex;
		temp = temp->next;
		if (visited[next] == false)
		{
			DFS(G, next);
		}
	}
}

//对所有节点进行深度遍历
void DFS_Main(AdjListGraph &G)
{
	for (int i = 0; i < G.vex; i++)
	{
		if (visited[i] == false)
		{
			DFS(G, i);
		}
	}
	for (int i = 0; i < Maxize; i++)
	{
		visited[i] = false;
	}
}

//对图上的顶点进行广度遍历
void BFS(AdjListGraph &G, int v)
{
	queue<int>q;
	int cur = -1;
	int index;

	q.push(v);

	while (!q.empty())
	{
		cur = q.front();
		if (visited[cur] == false)
		{
			cout << G.adjlist[cur].data << " ";
			visited[cur] = true;
		}

		q.pop();

		EdgeNode *temp = G.adjlist[cur].first;

		while (temp != NULL)
		{
			index = temp->adjvex;
			temp = temp->next;
			q.push(index);
		}
	}
}

//对所有节点进行广度遍历
void BFS_Main(AdjListGraph &G)
{
	for (int i = 0; i < G.vex; i++)
	{
		if (visited[i] == false)
		{
			BFS(G, i);
		}
	}
	for (int i = 0; i < Maxize; i++)
	{
		visited[i] = false;
	}
}



int main()
{
	AdjListGraph G;

	Init(G);

	Create(G);
	
	DFS_Main(G);

	cout << endl;

	BFS_Main(G);

	system("pause");
	return 0;
}
  • 9
    点赞
  • 56
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值