c實現隊列

使用鏈表實現隊列的入隊和出隊 node

#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);

}
相關文章
相關標籤/搜索