zoukankan      html  css  js  c++  java
  • 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("队列为空
    ");
      }
      else
      {
        x = headque->first->data;
        printf("num:%d
    ", 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("
    ");
    }
    
    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);
    
    }
  • 相关阅读:
    Linux进程和线程
    Vim编辑器
    Java多线程编程(七)线程状态、线程组与异常处理
    Java多线程编程(六)单例模式与多线程
    Integer to Roman
    Container With Most Water
    Regular Expression Matching
    Palindrome Number
    c/c++获取硬盘序列号
    String to Integer (atoi)
  • 原文地址:https://www.cnblogs.com/etangyushan/p/11194093.html
Copyright © 2011-2022 走看看