手机版
你好,游客 登录 注册
背景:
阅读新闻

深度优先遍历与广度优先遍历算法的C语言实现

[日期:2013-12-30] 来源:Linux社区  作者:Linux [字体:大 中 小]

queue.h

#ifndef H_QUEUE
#define H_QUEUE

#include <stdlib.h>

typedef struct _nodes {
    vertex *data;
    struct _nodes *next;
} node;

typedef struct _queue {
    int length;
    node *front;
    node *end;
} queue;

int push(queue *, vertex *);
int pop(queue *);

int push(queue *q, vertex *v)
{
    node *element;
    element = (node *)malloc(sizeof(node));

    element->data = v;
    element->next = NULL;
   
    if (q->length == 0)
    {
        q->front = element;
        q->end = element;
    }
    else
    {
        node *temp;
        temp = q->front;
        while (temp->next != NULL)
            temp = temp->next;
        temp->next = element;
        q->end = element;
    }

    q->length++;
}

int pop(queue *q)
{
    if (q->length == 0) return -1;

    node *temp;
    temp = q->front;
    q->front = q->front->next;
    q->length--;

    if (q->length == 1)
        q->end = NULL;

    free(temp);
}

#endif

bfs.h

#ifndef H_BFS
#define H_BFS

#include "graph.h"
#include "queue.h"
#include <stdio.h>

int bfs(graph *);

int bfs(graph *g)
{
    queue q;
    q.length = 0;
   
    push(&q, g->node_list[0]);
   
    int i;
    vertex *temp;
    temp = g->node_list[0];
    while (q.length > 0)
    {
        if (temp->alength > 0)
        {
            for (i = 0; i < temp->alength; i++)
                push(&q, temp->adjacency_nodes[i]);
            temp = temp->adjacency_nodes[0];
        }
        pop(&q);
    }
}

#endif

 

linux
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款