c实现队列

使用链表实现队列的入队和出队 

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

using namespace std;

//节点
typedef struct student
{
  int data;
  struct student *next;
}node;

//队列
typedef struct linkqueue
{
  node *first;  //队首节点 
  node *rear;   //队尾节点
}queue;

//入队
queue *insert(queue *headque, int x)
{
  //1. 定义变量
  node *s = NULL;
  
  //2. 新建节点
  s = (node*)malloc(sizeof(node));
  s->data = x;
  s->next = NULL;

  //3. 插入队尾
  if (headque->rear == NULL) //第一个节点
  {
    headque->first = s;
    headque->rear = s;
  }
  else
  {
    headque->rear->next = s;
    headque->rear = s;
  }

  //4. 返回队列
  return headque;
}

//出队
queue *del(queue *headque)
{
  //1. 定义变量
  node *p = NULL;
  int x = 0;

  //2. 节点出队
  if(headque->first == NULL) //队列为空
  {
    printf("队列为空\n");
  }
  else
  {
    x = headque->first->data;
    printf("num:%d\n", x);
    
    p = headque->first;
    if (headque->first == headque->rear) //到达队尾
    {
      headque->first = NULL;
      headque->rear = NULL;
    }
    else //删除节点
    {
      headque->first = headque->first->next;
      free(p);
      p = NULL;
    }
    
    //4. 返回队列
    return headque;
  }
}

//显示队列所有节点信息
void show(queue *headque)
{
  //1. 定义变量 
  node *p = NULL;
  int x = 0;

  //2. 遍历显示
  p = headque->first;
  while(p != NULL)
  {
    x = p->data;
    printf("%d ", x);
    p = p->next;
  }
  printf("\n");
}

int main()
{
 queue *headque = (queue*)malloc(sizeof(queue));
 insert(headque, 1);
 insert(headque, 2);
 insert(headque, 3);
 show(headque);
 del(headque);
 show(headque);
 del(headque);
 show(headque);

}

 

posted on 2019-07-16 12:15  欢跳的心  阅读(1957)  评论(0编辑  收藏  举报