Chinaunix首页 | 论坛 | 博客
  • 博客访问: 667052
  • 博文数量: 150
  • 博客积分: 4070
  • 博客等级: 中校
  • 技术积分: 1795
  • 用 户 组: 普通用户
  • 注册时间: 2010-12-23 21:44
文章分类

全部博文(150)

文章存档

2012年(1)

2011年(123)

2010年(26)

分类: IT业界

2011-06-09 15:15:12

1、链队列数据结构

struct queue

{

       int data;

       struct queue *next;

};

struct LinkQueue

{

       struct queue *head;

       struct queue *tail;

};

2、构造队列

struct LinkQueue CreateQueue()

{

       struct LinkQueue Q;

       Q.tail = Q.head = (struct queue *)malloc(sizeof(struct queue));

       if (Q.head == NULL)

       {

              exit(0);

       }

       Q.head->next = NULL;

       return Q;

}

3、销毁队列

void DestroyQueue(struct LinkQueue &Q)

{

       while (Q.head)

       {

              Q.tail = Q.head->next;

              delete Q.head;

              Q.head = Q.tail;

       }

}

4、清空队列

void ClearQueue(struct LinkQueue &Q)

{

       Q.tail = Q.head;

       struct queue *p = Q.head->next;

       Q.head->next = NULL;

       while (p != NULL)

       {

              struct queue *q = p;

              p = p->next;

              delete q;

       }

}

5、判断队列是否空

bool EmptyQueue(struct LinkQueue Q)

{

       if (Q.head == Q.tail)

              return true;

       else

              return false;

}

6、求队列的长度

int LengthQueue(struct LinkQueue Q)

{

       int length = 0;

       struct queue *p;

       p = Q.head->next;

       while (p != NULL)

       {

              length++;

              p = p->next;

       }

       return length;

}

7、返回队头元素

void GetQueueHead(struct LinkQueue Q, int &value)

{

       if (!EmptyQueue(Q))

       {

              struct queue *p = Q.head->next;

              value = p->data;

       }

}

8、元素入队列

void InsertQueue(struct LinkQueue &Q, int value)

{

       struct queue *newNode = new struct queue;

       newNode->data = value;

       newNode->next = NULL;

       Q.tail->next = newNode;

       Q.tail = newNode;      

}

9、删除队列头

void DelQueue(struct LinkQueue &Q, int &value)

{

       if (!EmptyQueue(Q))

       {

              struct queue *p;

              p = Q.head->next;

              value = p->data;

              Q.head->next = p->next;

              if (Q.tail == p)

              {

                     Q.tail = Q.head;

              }

              delete p;

       }

}

10、遍历队列元素

void QueueTraverse(struct LinkQueue Q)

{

       if (!EmptyQueue(Q))

       {

              struct queue *p = Q.head->next;

              while (p != NULL)

              {

                     printf("%d ", p->data);

                     p = p->next;

              }    

printf("\n");

       }

}

阅读(3046) | 评论(0) | 转发(1) |
给主人留下些什么吧!~~