鏈式隊列實現:
1.創建一個空隊列
2.尾插法入隊
3.頭刪法出隊
4.遍歷隊列
一、main函數
#include <stdio.h> #include "./3.linkqueue.h" int main(int argc, const char *argv[]) { linkpos* pos = create_linkqueue(); show_linkqueue(pos);insertENd_linkqueue(pos,111); insertENd_linkqueue(pos,222); insertENd_linkqueue(pos,333); insertENd_linkqueue(pos,444); insertENd_linkqueue(pos,555); show_linkqueue(pos); dataType num = output_linkqueue(pos); printf("出隊的數據為:%d\n",num); show_linkqueue(pos); return 0; }
二、功能函數
#include <stdio.h>
#include <stdlib.h>
#include "./3.linkqueue.h" //創建
linkpos* create_linkqueue()
{ linkpos* pos = (linkpos*)malloc(sizeof(linkpos)); pos->front = (linkqueue*)malloc(sizeof(linkqueue)); if(NULL == pos->front) { printf("隊列創建失敗\n"); return NULL; } pos->front->next =NULL; pos->rear = pos->front; pos->front->text.len = 0; return pos;
} //判空
int isEmpty_linkqueue(linkpos*pos)
{ return pos->front == pos->rear?1:0;
} //遍歷
void show_linkqueue(linkpos*pos)
{ if(isEmpty_linkqueue(pos)) { printf("隊列為空!\n"); return ; } linkqueue* p = pos->front->next; while(p != pos->rear) { printf("%d ",p->text.data); p=p->next; } printf("\n"); return ;
} //尾插 入隊
void insertENd_linkqueue(linkpos*pos,dataType num)
{ linkqueue* temp = (linkqueue*)malloc(sizeof(linkqueue)); if(NULL == temp) { printf("結點創建失敗,入隊失敗\n"); return; } temp->next = NULL; temp->text.data = num; temp->next = pos->rear->next; pos->rear->next = temp; pos->rear = pos->rear->next; pos->front->text.len++; return; } //頭刪 出隊
dataType output_linkqueue(linkpos*pos)
{ if(isEmpty_linkqueue(pos)) { printf("隊列為空,無法出隊\n"); return (dataType)-1; } linkqueue* temp; temp = pos->front->next; pos->front->next = temp->next; dataType num =temp->text.data; if(pos->front->next == NULL) {pos->rear = pos->front;} free(temp); return num;
}
三、頭文件
#ifndef __LINKQUEUE_H__#define __LINKQUEUE_H__typedef int dataType;union msg{dataType data;int len;};typedef struct node{union msg text;struct node* next;}linkqueue;typedef struct{linkqueue* front;linkqueue* rear;}linkpos;linkpos* create_linkqueue();void insertENd_linkqueue(linkpos*pos,dataType num);dataType output_linkqueue(linkpos*pos);void show_linkqueue(linkpos*pos); #endif