1.實現單向鏈表隊列的,創建,入隊,出隊,遍歷,長度,銷毀。
main.c
#include "head.h"int main(int argc, const char *argv[])
{//創建鏈式隊列queue_ptr QL=create_queue();//入棧push(QL, 1000);push(QL, 1001);push(QL, 1002);push(QL, 1003);push(QL, 1004);//遍歷 output(QL);//出隊pop( QL);output(QL);//長度length(QL);//銷毀 freedom(QL);return 0;
}
head.h
#ifndef __HEAD_H__
#define __HEAD_H__ #include <stdio.h>
#include <stdlib.h>
//定義節點中的數據類型
typedef int datatype;
//定義節點結構體
typedef struct node
{ union { int len; datatype data; }; struct node*next;
}Node; //定義鏈式隊列結構體
typedef struct seq
{ Node *head; Node *tail;
}queue,*queue_ptr; //1.創建鏈式隊列
queue_ptr create_queue();
//2.判斷為空操作
int empty(queue_ptr QL);
//3.鏈式隊列入隊
int push(queue_ptr QL,datatype e);
//4.鏈式隊列的遍歷
void output(queue_ptr QL);
//5,鏈式隊列的出隊只能從對頭刪除
void pop(queue_ptr QL);
//6.長度
void length(queue_ptr QL);
//銷毀
void freedom(queue_ptr QL);
#endif
?fun.c
#include "head.h" //1.創建鏈式隊列 queue_ptr create_queue() { //申請鏈式隊列的結構體的大小空間 queue_ptr QL=(queue_ptr)malloc(sizeof(queue)); //判斷鏈式隊列申請節點成功沒有 if(NULL==QL) { printf("創建鏈式隊列失敗\n"); return NULL; } //申請節點結構體的大小空間 QL->head=(Node*)malloc(sizeof(Node)); //判斷鏈式隊列節點申請有沒有成功 if(NULL==QL->head) { printf("節點創建失敗\n"); free(QL); return NULL; } //頭節點創建成功 QL->head->len=0;//節點長度置0 QL->head->next=NULL;//節點指針域指向NULL //鏈式隊列結構體里面的指針指向 QL->tail=QL->head; printf("鏈式隊列創建成功\n"); return QL; } //2.判斷為空操作 int empty(queue_ptr QL) { if(QL==NULL) { printf("判空操作失敗\n"); return -1; } //當鏈式隊列結構體的指針指向同一個節點 return QL->head==QL->tail; } //3.鏈式隊列入隊 int push(queue_ptr QL,datatype e) { if(QL==NULL) { printf("入隊失敗\n"); return 0; } //申請普通節點 Node *p=(Node*)malloc(sizeof(Node)); if(NULL==p) { printf("申請節點失敗\n"); return 0; } p->data=e; p->next=NULL; //然后尾插 QL->tail->next=p; QL->tail=p; //長度自增 QL->head->len++; return 1; } //4.鏈式隊列的遍歷 void output(queue_ptr QL) { if(NULL==QL ||empty(QL)) { printf("遍歷失敗\n"); return ; } //循環遍歷的指向的指針 Node* q=QL->head; while(q->next!=NULL) { q=q->next; printf("%d ",q->data); } printf("\n"); } //5,鏈式隊列的出隊只能從對頭刪除 void pop(queue_ptr QL) { if(NULL==QL ||empty(QL)) { printf("出隊失敗\n"); return ; } //定義一個遍歷指向隊頭指針 Node*p=QL->head->next; //頭指針指向下一節點 QL->head->next=p->next; free(p); p=NULL; QL->head->len--; } //6.長度 void length(queue_ptr QL) { if(NULL==QL) { printf("輸出長度失敗\n"); return ; } int len=QL->head->len; printf("該順序鏈式隊列的長度為:%d\n",len); return; } //銷毀 void freedom(queue_ptr QL) { if(NULL==QL) { printf("銷毀失敗\n"); return ; } while(QL->head->next!=NULL) { pop(QL); } free(QL->head); QL->head=NULL; printf("銷毀成功\n"); return;
}
?