[C&&C++]数据结构基本操作

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Aless0/article/details/79981419

顺序表:

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

// 函数结果状态码
#define OK 1
#define ERROR 0
#define OVERFLOW -2

typedef int Status; // Status是函数返回值类型,其值是函数结果状态码

#define MAXSIZE 1024 // 顺序表可能达到的最大长度

typedef int ElemType; // 元素数据类型

typedef struct {
	ElemType *elem; // 指向数据元素的基地址
	int length; // 当前长度
}SqList; // 顺序表

/* 顺序表基本操作,序号i从1开始 */
// 销毁
void destroyList(SqList &L){
	free(L.elem);
	L.elem = NULL;
} 

// 根据用户输入,创建n个元素的表 
Status createList(SqList &L,int n)
{
	L.elem = new ElemType[MAXSIZE];
	if(!L.elem) exit(OVERFLOW);
	for(int i = 1; i <= n; i++)
		scanf("%d",&L.elem[i]);
	L.length = n;
	return OK;
}

// 遍历,打印表中元素 
void traverseList(SqList L)
{
	for(int i = 1; i <= L.length; i++)
		printf("%d ",L.elem[i]);
}

// 取值,将序号i的元素存入e 
Status getElem(SqList L, int i, ElemType &e)
{
	if(i < 1 || i > L.length) return ERROR;
	e = L.elem[i];
	return OK;
}

// 查找,返回元素e的序号 
int locateElem(SqList L, ElemType e)
{
	for(int i = 1; i <= L.length; i++)
		if(L.elem[i] == e) return i;
	return 0; 
}

// 插入 
Status listInsert(SqList &L, int i, ElemType e)
{
	if((i < 1) || (i > L.length + 1)) return ERROR;
	if(L.length == MAXSIZE) return ERROR;
	for(int j = L.length; j >= i; j--)
		L.elem[j+1] = L.elem[j];
	L.elem[i] = e;
	++L.length;
	return OK;
}

// 删除 
Status listDelete(SqList &L, int i)
{
	if((i < 1) || (i > L.length)) return ERROR;
	for(int j = i; j <= L.length - 1; j++)
		L.elem[j] = L.elem[j+1];
	--L.length;
	return OK;
}

int main(){
	SqList list;
	int e, n, m;
	scanf("%d",&n);
	createList(list,n);
	scanf("%d",&m);
	if(getElem(list,m,e) == OK){ //把 e 赋值为链表里的第 m 个数 
		printf("The value of e is %d\n",e);
	}else{
		printf("There is no m number in the list.\n");
	}
	scanf("%d", &e);
	if(locateElem(list,e)){
		printf("The index of %d is %d\n",e,locateElem(list,e));
	}else{
		printf("There is no number %d in the list.\n",e);
	}
	scanf("%d %d",&m,&e); // 插入元素 e 到第 m 个位置 
	if(listInsert(list,m,e) == OK){
		traverseList(list); 
	}else{
		printf("Insert Error\n");
	}
	scanf("%d",&m); // 删除第 m 个元素 
	if(listDelete(list,m) == OK){
		traverseList(list); 
	}else{
		printf("Delete Error\n");
	}
	destroyList(list);
}

链表:

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

// 函数结果状态码
#define OK 1
#define ERROR 0
#define OVERFLOW -2

typedef int Status; // Status是函数返回值类型,其值是函数结果状态码

typedef int ElemType; // 元素数据类型 

typedef struct LNode
{
	ElemType data; // 数据域
	struct LNode *next; // 指针域
}LNode,*LinkList;

/* 基本操作,序号i从1开始 */
// 遍历,打印表中元素 
Status createList(LinkList &L,int n)
{
	L = new LNode;
	L->next = NULL;
	LNode *r = L;
	for(int i = 0; i < n; i++)
	{
		LNode *p = new LNode;
		scanf("%d",&p->data);
		p->next = NULL;
		r->next = p;
		r = p;
	}
}

Status getElem(LinkList L, int i, ElemType &e)
{
	LNode *p = L->next;
	int j = 1;
	while(p && j < i)
	{
		p = p->next;
		++j;
	}
	if(!p || j > i) return ERROR;
	e = p->data;
	return OK;
}

int locateElem(LinkList L, ElemType e)
{
	LNode *p = L->next;
	int i = 1;
	while(p && p->data != e)
	{
		i++;
		p = p->next;
	}
	if(!p) return 0;
	return i;
}

Status listInsert(LinkList &L, int i, ElemType e)
{
	LNode *p = L;
	int j = 0;
	while(p && (j < i - 1))
	{
		p = p->next;
		++j;
	}
	if(!p || j > i - 1) return ERROR;
	LNode *s = new LNode;
	s->data = e;
	s->next = p->next;
	p->next = s;
	return OK;
}

Status listDelete(LinkList &L, int i)
{
	LNode *p = L;
	int j = 0;
	while((p->next)&&(j < i - 1))
	{
		p = p->next;
		++j;
	}
	if(!(p->next) || (j > i - 1)) return ERROR;
	LNode *q = p->next;
	p->next = q->next;
	delete q;
	return OK;
}

void traverseList(LinkList L){
	LNode *p = L->next;
	while(p){
		printf("%d ",p->data);
		p = p->next;
	}
	printf("\n");
}

int main(){
	LinkList list;
	int cmd, result, e, n, i;
	scanf("%d", &n); 
	createList(list, n);
	while (~scanf("%d", &cmd) && cmd!=-1) { // 选择操作 
		switch (cmd) {
		case 0:			// 取值
			scanf("%d", &i);
			result = getElem(list, i, e);
			if (result) printf("%d\n", e);
			else printf("Failed\n");
			break;
		case 1:			// 查找
			scanf("%d", &e);
			result = locateElem(list, e);
			if (result) printf("%d\n", result);
			else printf("Failed\n");
			break;
		case 2:				// 显示 
			traverseList(list);
			break;
		case 3:				// 插入 
			scanf("%d%d", &i, &e);
			result = listInsert(list, i, e); 
			if (result) printf("Succeed\n");
			else printf("Failed\n");
			break;
		case 4:				// 删除 
			scanf("%d", &i);
			result = listDelete(list, i); 
			if (result) printf("Succeed\n");
			else printf("Failed\n");
			break;
		default:
			printf("Unknown Command.\n");
			break;
		}
	}
	return 0;
}

顺序栈:

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

// 函数结果状态码 
typedef int Status;
#define OK 1
#define ERROR 0
#define OVERFLOW -2

#define  MAXSIZE  10	//初始最大容量
typedef int SElemType;
typedef struct{
	SElemType   *base;	//栈底
	SElemType   *top;	//栈顶
}SqStack;

Status init(SqStack &s);	// 初始化一个空栈 
Status push(SqStack &s, SElemType e); 	// 元素e入栈 
Status pop(SqStack &s);				// 出栈 
Status getTop(SqStack s, SElemType &e);	// 将栈顶元素赋值给e 
void clear(SqStack &s);					// 清空栈 
void printSqStack(SqStack s);	//按输入的顺序打印栈中的元素 

int main(){
	int cmd, x;
	SqStack s;
	init(s); 
	while(~scanf("%d",&cmd)){
		switch(cmd){
			case 1:
				scanf("%d",&x);
				if(!push(s,x)) printf("full\n");
				break;
			case 2:
				if(!pop(s)) printf("empty\n");
				break;
			case 3:
				clear(s);
				break;
			case 4:
				if(getTop(s, x)) printf("%d\n", x);
				else printf("empty\n");
				break;
			case 5:
				printSqStack(s);
				break;
			default:
				printf("Unknown Command\n");
				break;
		}
	}
}
Status init(SqStack &s)
{
	s.base = new SElemType[MAXSIZE];
	if(!s.base) exit(OVERFLOW);
	s.top = s.base;
	return OK;
}

Status push(SqStack &s, SElemType e)
{
	if(s.top - s.base == MAXSIZE) return ERROR;
	*s.top++=e; // 元素e压入top,top+1
	return OK;
}

Status pop(SqStack &s)
{
	if(s.top == s.base) return ERROR;
	int e=*--s.top;
	return OK;
}

Status getTop(SqStack s, SElemType &e)
{
	if(s.top != s.base)
		e = *(s.top-1);
	return OK;
}

void clear(SqStack &s)
{
	s.top = s.base;
}

void printSqStack(SqStack s){
	if(s.top == s.base)
		printf("empty");
	while(s.top != s.base){
		printf("%d ",*--s.top);
	}
	
	printf("\n");
}

链栈:

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

// 函数结果状态码 
typedef int Status;
#define OK 1
#define ERROR 0
#define OVERFLOW -2

typedef int SElemType;	// 元素数据类型 

typedef struct LNode{
	SElemType data;
	struct LNode *next;
}StackNode, *LinkStack;

void init(LinkStack &s);		// 初始化一个空栈 
Status push(LinkStack &s, SElemType e); 	// 元素e入栈 
Status pop(LinkStack &s);					// 出栈 
Status getTop(LinkStack s, SElemType &e);	// 将栈顶元素赋值给e 
void clear(LinkStack &s);					// 清空栈 
void printLinkStack(LinkStack s);	//按输入的顺序打印栈中的元素 

int main(){
	int cmd, x;
	LinkStack s;
	init(s); 
	while(~scanf("%d",&cmd)){
		switch(cmd){
			case 1:
				scanf("%d",&x);
				if(!push(s,x)) printf("full\n");
				break;
			case 2:
				if(!pop(s)) printf("empty\n");
				break;
			case 3:
				clear(s);
				break;
			case 4:
				if(getTop(s, x)) printf("%d\n", x);
				else printf("empty\n");
				break;
			case 5:
				printLinkStack(s);
				break;
			default:
				printf("Unknown Command\n");
				break;
		}
	}
}
void init(LinkStack &s)
{
	s = NULL;
}

Status push(LinkStack &s, SElemType e)
{
	StackNode *p = new StackNode;
	p->data = e;
	p->next = s;
	s = p;
	return OK;
}

Status pop(LinkStack &s)
{
	if(s == NULL) return ERROR;
	StackNode *p = s;
	s = s->next;
	delete p;
	return OK;
}

Status getTop(LinkStack s, SElemType &e)
{
	if(s != NULL)
		e = s->data;
	return OK;
}

void clear(LinkStack &s)
{
	while(s != NULL)
		pop(s);
}

void printLinkStack(LinkStack s)
{
	if(s == NULL)
		printf("empty\n");
	else
	{
		StackNode *p = s;
		while(p)
		{
			printf("%d ",p->data);
			p = p->next;
		}
		printf("\n");
	}
}

循环队列:

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

// 函数结果状态码 
typedef int Status;
#define OK 1
#define ERROR 0
#define OVERFLOW -2

#define  MAXSIZE  10	 
typedef int QElemType;
typedef struct{
	QElemType   *base;	//存储空间的基地址 
	int front;			// 队头
	int rear;			// 队尾 
}SqQueue;

Status init(SqQueue &q);	// 初始化一个空队列 
Status enqueue(SqQueue &q, QElemType e); 	// 元素e入队 
Status dequeue(SqQueue &q);					// 出队 
Status getFront(SqQueue q, QElemType &e);	// 将队头元素赋值给e 
void clear(SqQueue &q);					// 清空队列 
void printSqQueue(SqQueue q);	//按输入的顺序打印队列中的元素 

int main(){
	int cmd, x;
	SqQueue q;
	init(q); 
	while(~scanf("%d",&cmd)){
		switch(cmd){
			case 1:
				scanf("%d",&x);
				if(!enqueue(q,x)) printf("full\n");
				break;
			case 2:
				if(!dequeue(q)) printf("empty\n");
				break;
			case 3:
				clear(q);
				break;
			case 4:
				if(getFront(q, x)) printf("%d\n", x);
				else printf("empty\n");
				break;
			case 5:
				printSqQueue(q);
				break;
			default:
				printf("Unknown Command\n");
				break;
		}
	}
}
Status init(SqQueue &q)
{
	q.base = new QElemType[MAXSIZE];
	if(!q.base) exit(OVERFLOW);
	q.front = q.rear = 0;
	return OK;
}

Status enqueue(SqQueue &q, QElemType e)
{
	if((q.rear + 1) % MAXSIZE == q.front) return ERROR;
	q.base[q.rear] = e;
	q.rear = (q.rear + 1) % MAXSIZE;
	return OK;
}

Status dequeue(SqQueue &q)
{
	if(q.front == q.rear) return ERROR;
	q.front = (q.front + 1) % MAXSIZE;
	return OK;
}

Status getFront(SqQueue q, QElemType &e)
{
	if(q.front != q.rear)
	{
		e = q.base[q.front];
		return OK;
	}
	else return ERROR;
}

void clear(SqQueue &q)
{
	q.front = q.rear = 0;
}

void printSqQueue(SqQueue q)
{
	int x;
	int cnt = 0;
	int nums[100];
	if(q.front == q.rear)
	{
		printf("empty\n");
		return;
	}
	else
	{
		while(q.front != q.rear)
		{
			getFront(q,x);
			dequeue(q);
			nums[cnt++] = x;
		}
	
		for(int i = 0; i < cnt; i++)
			printf("%d ",nums[i]);
		printf("\n");
	}
}

链队:

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

// 函数结果状态码 
typedef int Status;
#define OK 1
#define ERROR 0
#define OVERFLOW -2

typedef int QElemType;	// 元素数据类型 

typedef struct QNode{
	QElemType data;
	struct QNode *next;
}QNode, *QueuePtr;

typedef struct{
	QueuePtr front;	// 队头  
	QueuePtr rear;	// 队尾 
} LinkQueue;

void init(LinkQueue &q);		// 初始化一个空队列 
Status enqueue(LinkQueue &q, QElemType e); 	// 元素e入队 
Status dequeue(LinkQueue &q);					// 出队 
Status getFront(LinkQueue q, QElemType &e);	// 将队头元素赋值给e 
void clear(LinkQueue &q);					// 清空队列 
void printLinkQueue(LinkQueue q);	//按输入的顺序打印队列中的元素 

int main(){
	int cmd, x;
	LinkQueue q;
	init(q); 
	while(~scanf("%d",&cmd)){
		switch(cmd){
			case 1:
				scanf("%d",&x);
				if(!enqueue(q,x)) printf("full\n");
				break;
			case 2:
				if(!dequeue(q)) printf("empty\n");
				break;
			case 3:
				clear(q);
				break;
			case 4:
				if(getFront(q, x)) printf("%d\n", x);
				else printf("empty\n");
				break;
			case 5:
				printLinkQueue(q);
				break;
			default:
				printf("Unknown Command\n");
				break;
		}
	}
}

void init(LinkQueue &q)
{
	q.front = q.rear = new QNode;
	q.front->next = NULL;
}

Status enqueue(LinkQueue &q, QElemType e)
{
	QNode *p = new QNode;
	p->data = e;
	p->next = NULL;
	q.rear->next = p;
	q.rear = p;
	return OK;
}

Status dequeue(LinkQueue &q)
{
	if(q.front == q.rear) return ERROR;
	QNode *p = q.front->next;
	q.front->next = p->next;
	if(q.rear == p) q.rear = q.front;
	delete p;
	return OK;
}

Status getFront(LinkQueue q, QElemType &e)
{
	if(q.front != q.rear)
	{
		e = q.front->next->data;
		return OK;
	}
	else return ERROR;
}

void clear(LinkQueue &q)
{
	while(q.front != q.rear)
		dequeue(q);
}

void printLinkQueue(LinkQueue q)
{
	if(q.front == q.rear) printf("empty\n");
	else
	{
		while(q.front != q.rear)
		{
			q.front = q.front->next;
			printf("%d ",q.front->data);
		}
	printf("\n");
	}
}

图(Graph):

/* 图的邻接矩阵表示法 */
 
#define MaxVertexNum 100    /* 最大顶点数设为100 */
#define INFINITY 65535        /* ∞设为双字节无符号整数的最大值65535*/
typedef int Vertex;         /* 用顶点下标表示顶点,为整型 */
typedef int WeightType;        /* 边的权值设为整型 */
typedef char DataType;        /* 顶点存储的数据类型设为字符型 */
 
/* 边的定义 */
typedef struct ENode *PtrToENode;
struct ENode{
    Vertex V1, V2;      /* 有向边<V1, V2> */
    WeightType Weight;  /* 权重 */
};
typedef PtrToENode Edge;
        
/* 图结点的定义 */
typedef struct GNode *PtrToGNode;
struct GNode{
    int Nv;  /* 顶点数 */
    int Ne;  /* 边数   */
    WeightType G[MaxVertexNum][MaxVertexNum]; /* 邻接矩阵 */
    DataType Data[MaxVertexNum];      /* 存顶点的数据 */
    /* 注意:很多情况下,顶点无数据,此时Data[]可以不用出现 */
};
typedef PtrToGNode MGraph; /* 以邻接矩阵存储的图类型 */
 
 
 
MGraph CreateGraph( int VertexNum )
{ /* 初始化一个有VertexNum个顶点但没有边的图 */
    Vertex V, W;
    MGraph Graph;
     
    Graph = (MGraph)malloc(sizeof(struct GNode)); /* 建立图 */
    Graph->Nv = VertexNum;
    Graph->Ne = 0;
    /* 初始化邻接矩阵 */
    /* 注意:这里默认顶点编号从0开始,到(Graph->Nv - 1) */
    for (V=0; V<Graph->Nv; V++)
        for (W=0; W<Graph->Nv; W++)  
            Graph->G[V][W] = INFINITY;
             
    return Graph; 
}
        
void InsertEdge( MGraph Graph, Edge E )
{
     /* 插入边 <V1, V2> */
     Graph->G[E->V1][E->V2] = E->Weight;    
     /* 若是无向图,还要插入边<V2, V1> */
     Graph->G[E->V2][E->V1] = E->Weight;
}
 
MGraph BuildGraph()
{
    MGraph Graph;
    Edge E;
    Vertex V;
    int Nv, i;
     
    scanf("%d", &Nv);   /* 读入顶点个数 */
    Graph = CreateGraph(Nv); /* 初始化有Nv个顶点但没有边的图 */ 
     
    scanf("%d", &(Graph->Ne));   /* 读入边数 */
    if ( Graph->Ne != 0 ) { /* 如果有边 */ 
        E = (Edge)malloc(sizeof(struct ENode)); /* 建立边结点 */ 
        /* 读入边,格式为"起点 终点 权重",插入邻接矩阵 */
        for (i=0; i<Graph->Ne; i++) {
            scanf("%d %d %d", &E->V1, &E->V2, &E->Weight); 
            /* 注意:如果权重不是整型,Weight的读入格式要改 */
            InsertEdge( Graph, E );
        }
    } 
 
    /* 如果顶点有数据的话,读入数据 */
    for (V=0; V<Graph->Nv; V++) 
        scanf(" %c", &(Graph->Data[V]));
 
    return Graph;
}
/* 图的邻接表表示法 */
 
#define MaxVertexNum 100    /* 最大顶点数设为100 */
typedef int Vertex;         /* 用顶点下标表示顶点,为整型 */
typedef int WeightType;        /* 边的权值设为整型 */
typedef char DataType;        /* 顶点存储的数据类型设为字符型 */
 
/* 边的定义 */
typedef struct ENode *PtrToENode;
struct ENode{
    Vertex V1, V2;      /* 有向边<V1, V2> */
    WeightType Weight;  /* 权重 */
};
typedef PtrToENode Edge;
 
/* 邻接点的定义 */
typedef struct AdjVNode *PtrToAdjVNode; 
struct AdjVNode{
    Vertex AdjV;        /* 邻接点下标 */
    WeightType Weight;  /* 边权重 */
    PtrToAdjVNode Next;    /* 指向下一个邻接点的指针 */
};
 
/* 顶点表头结点的定义 */
typedef struct Vnode{
    PtrToAdjVNode FirstEdge;/* 边表头指针 */
    DataType Data;            /* 存顶点的数据 */
    /* 注意:很多情况下,顶点无数据,此时Data可以不用出现 */
} AdjList[MaxVertexNum];    /* AdjList是邻接表类型 */
 
/* 图结点的定义 */
typedef struct GNode *PtrToGNode;
struct GNode{  
    int Nv;     /* 顶点数 */
    int Ne;     /* 边数   */
    AdjList G;  /* 邻接表 */
};
typedef PtrToGNode LGraph; /* 以邻接表方式存储的图类型 */
 
 
 
LGraph CreateGraph( int VertexNum )
{ /* 初始化一个有VertexNum个顶点但没有边的图 */
    Vertex V;
    LGraph Graph;
     
    Graph = (LGraph)malloc( sizeof(struct GNode) ); /* 建立图 */
    Graph->Nv = VertexNum;
    Graph->Ne = 0;
    /* 初始化邻接表头指针 */
    /* 注意:这里默认顶点编号从0开始,到(Graph->Nv - 1) */
       for (V=0; V<Graph->Nv; V++)
        Graph->G[V].FirstEdge = NULL;
             
    return Graph; 
}
        
void InsertEdge( LGraph Graph, Edge E )
{
    PtrToAdjVNode NewNode;
     
    /* 插入边 <V1, V2> */
    /* 为V2建立新的邻接点 */
    NewNode = (PtrToAdjVNode)malloc(sizeof(struct AdjVNode));
    NewNode->AdjV = E->V2;
    NewNode->Weight = E->Weight;
    /* 将V2插入V1的表头 */
    NewNode->Next = Graph->G[E->V1].FirstEdge;
    Graph->G[E->V1].FirstEdge = NewNode;
         
    /* 若是无向图,还要插入边 <V2, V1> */
    /* 为V1建立新的邻接点 */
    NewNode = (PtrToAdjVNode)malloc(sizeof(struct AdjVNode));
    NewNode->AdjV = E->V1;
    NewNode->Weight = E->Weight;
    /* 将V1插入V2的表头 */
    NewNode->Next = Graph->G[E->V2].FirstEdge;
    Graph->G[E->V2].FirstEdge = NewNode;
}
 
LGraph BuildGraph()
{
    LGraph Graph;
    Edge E;
    Vertex V;
    int Nv, i;
     
    scanf("%d", &Nv);   /* 读入顶点个数 */
    Graph = CreateGraph(Nv); /* 初始化有Nv个顶点但没有边的图 */ 
     
    scanf("%d", &(Graph->Ne));   /* 读入边数 */
    if ( Graph->Ne != 0 ) { /* 如果有边 */ 
        E = (Edge)malloc( sizeof(struct ENode) ); /* 建立边结点 */ 
        /* 读入边,格式为"起点 终点 权重",插入邻接矩阵 */
        for (i=0; i<Graph->Ne; i++) {
            scanf("%d %d %d", &E->V1, &E->V2, &E->Weight); 
            /* 注意:如果权重不是整型,Weight的读入格式要改 */
            InsertEdge( Graph, E );
        }
    } 
 
    /* 如果顶点有数据的话,读入数据 */
    for (V=0; V<Graph->Nv; V++) 
        scanf(" %c", &(Graph->G[V].Data));
 
    return Graph;
}

/* 邻接矩阵存储的图 - BFS */
 
/* IsEdge(Graph, V, W)检查<V, W>是否图Graph中的一条边,即W是否V的邻接点。  */
/* 此函数根据图的不同类型要做不同的实现,关键取决于对不存在的边的表示方法。*/
/* 例如对有权图, 如果不存在的边被初始化为INFINITY, 则函数实现如下:         */
bool IsEdge( MGraph Graph, Vertex V, Vertex W )
{
    return Graph->G[V][W]<INFINITY ? true : false;
}
 
/* Visited[]为全局变量,已经初始化为false */
void BFS ( MGraph Graph, Vertex S, void (*Visit)(Vertex) )
{   /* 以S为出发点对邻接矩阵存储的图Graph进行BFS搜索 */
    Queue Q;     
    Vertex V, W;
 
    Q = CreateQueue( MaxSize ); /* 创建空队列, MaxSize为外部定义的常数 */
    /* 访问顶点S:此处可根据具体访问需要改写 */
    Visit( S );
    Visited[S] = true; /* 标记S已访问 */
    AddQ(Q, S); /* S入队列 */
     
    while ( !IsEmpty(Q) ) {
        V = DeleteQ(Q);  /* 弹出V */
        for( W=0; W<Graph->Nv; W++ ) /* 对图中的每个顶点W */
            /* 若W是V的邻接点并且未访问过 */
            if ( !Visited[W] && IsEdge(Graph, V, W) ) {
                /* 访问顶点W */
                Visit( W );
                Visited[W] = true; /* 标记W已访问 */
                AddQ(Q, W); /* W入队列 */
            }
    } /* while结束*/
}
/* 邻接表存储的图 - DFS */
 
void Visit( Vertex V )
{
    printf("正在访问顶点%d\n", V);
}
 
/* Visited[]为全局变量,已经初始化为false */
void DFS( LGraph Graph, Vertex V, void (*Visit)(Vertex) )
{   /* 以V为出发点对邻接表存储的图Graph进行DFS搜索 */
    PtrToAdjVNode W;
     
    Visit( V ); /* 访问第V个顶点 */
    Visited[V] = true; /* 标记V已访问 */
 
    for( W=Graph->G[V].FirstEdge; W; W=W->Next ) /* 对V的每个邻接点W->AdjV */
        if ( !Visited[W->AdjV] )    /* 若W->AdjV未被访问 */
            DFS( Graph, W->AdjV, Visit );    /* 则递归访问之 */
}

无向图邻接矩阵表示法+DFS&&BFS遍历:

#include<stdio.h>
#include<string.h>
#include<queue>
using namespace std;

#define MVNum 100                       	//最大顶点数 
typedef char VertexType;              	//假设顶点的数据类型为字符型 
typedef int ArcType;                  	//假设边的权值类型为整型 
typedef struct{ 
  	VertexType vexs[MVNum];            		//顶点表 
  	ArcType arcs[MVNum][MVNum];      	//邻接矩阵 
  	int vexnum,arcnum;                	//图的当前点数和边数 
}AMGraph; 

void create(AMGraph &g)
{
	scanf("%d %d", &g.vexnum, &g.arcnum);
	getchar();
	for (int i = 0; i < g.vexnum; i++)
	{
		scanf("%c", &g.vexs[i]);
		getchar();
	}
	for (int i = 0; i < MVNum; i++){
		for (int j = 0; j < MVNum; j++){
			g.arcs[i][j] = 0;
		}
	}
	char u,v;
	for (int i = 0; i < g.arcnum; i++){
		scanf("%c %c",&u,&v);
		getchar();
		int m = -1, n = -1, k;
		for ( k = 0; k < g.vexnum; k++)
		{
			if(g.vexs[k] == u) m = k;
			if(g.vexs[k] == v) n = k;
		} 
		g.arcs[m][n] = 1;
		g.arcs[n][m] = 1;
	}

void dfs(AMGraph &g, int v)
{
	visited[v] = 1;
	printf("%c ",g.vexs[v]);
	for(int w = 0;w < g.vexnum; w++)
	{
		if((g.arcs[v][w] != 0) && (!visited[w]))
			dfs(g,w);
	}
}

void bfs(AMGraph &g, int v)
{
	printf("%c ",g.vexs[v]);
	visited[v] = 1;
	queue<int> q;
	q.push(v);
	while(!q.empty())
	{
		int u = q.front();
		q.pop();
		for(int i = 0;i < g.vexnum;i++)
		{
			if(!visited[i] && g.arcs[u][i] != 0)
			{
				printf("%c ",g.vexs[i]);
				visited[i] = 1;
				q.push(i);
			}
		}
	}
}

int main(){
	AMGraph g;
	create(g);
	memset(visited, 0, sizeof(visited));
	dfs(g, 0);
	printf("\n");
	memset(visited, 0, sizeof(visited));
	bfs(g, 0);
	printf("\n");
	
}

无向图的邻接表表示方法+DFS&&BFS遍历:

#include<stdio.h>
#include<string.h>
#include<queue>
using namespace std;

#define MVNum 10

typedef char VextexType;
typedef struct ArcNode {
       int adjvex;			// 该边的起始点位置(下标)
       struct ArcNode *nextarc;   	 // 指向下一条边的指针
}ArcNode;	 // 边结点 

typedef struct { 	
       VextexType data; 	// 顶点信息
       ArcNode *firstarc;   	// 指向第一条依附该顶点的边 
}VNode;	  // 顶点结点 

typedef struct 	
{     VNode vertices[MVNum];	// 顶点数组 
      int vexnum, arcnum; 	  	 // 当前顶点数和边数
}ALGraph;    // 邻接表 



void create(ALGraph &g)
{
	scanf("%d %d", &g.vexnum, &g.arcnum);
	getchar();
	for (int i = 0; i < g.vexnum; i++)
	{
		scanf("%c", &g.vertices[i].data);
		getchar();
		g.vertices[i].firstarc = NULL;
	}
	char u,v;
	for (int i = 0; i < g.arcnum; i++)
	{
		scanf("%c %c",&u,&v);
		getchar();
		int m = -1, n = -1, k;
		for (k = 0; k < g.vexnum; k++)
		{
			if(g.vertices[k].data == u) m = k;
			if(g.vertices[k].data == v) n = k;
		} 
		ArcNode *p = new ArcNode;
		p->adjvex = n;
		p->nextarc = g.vertices[m].firstarc;
		g.vertices[m].firstarc = p;
		
		p = new ArcNode;
		p->adjvex = m;
		p->nextarc = g.vertices[n].firstarc;
		g.vertices[n].firstarc = p;
	}
}

void dfs(ALGraph &g, int v)
{
    printf("%c ", g.vertices[v].data);
	visited[v]=1;
	ArcNode *p = g.vertices[v].firstarc;
	while(p)
	{
		int w = p->adjvex;
		if(!visited[w]){
			dfs(g, w);
		}
		p = p->nextarc;
	}
}

void bfs(ALGraph &g, int v)
{
	queue<int> q;
	printf("%c ", g.vertices[v].data);
	visited[v]=1;
	q.push(v);
	while(!q.empty())
	{
		int u = q.front();
		q.pop();
		ArcNode *p = g.vertices[u].firstarc;
		while(p)
		{
			int w = p->adjvex;
			if(!visited[w])
			{
				printf("%c ", g.vertices[w].data);
				visited[w] = 1;
				q.push(w);
			}
			p = p->nextarc;
		}
	}    
}

int main()
{
	ALGraph g;
	create(g);
	memset(visited, 0, sizeof(visited));
	dfs(g, 0);
	printf("\n");
	memset(visited, 0, sizeof(visited));
	bfs(g, 0);
	printf("\n");
}
阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页