1,將1-9入隊列
2,出隊列
3,進棧
4,出棧
#include<stdio.h> #include<stdlib.h> #include "stack.h"; #define Capacity 9 typedef struct Node { int data; struct Node* next; }node; //定義一個鏈隊列 typedef struct LinkQueue { node* front; //隊首結點 node* rear; //隊尾結點 }LQ; //初始化空鏈隊列 LQ initLQ(LQ LQ) { LQ.front = (node*)malloc(sizeof(node)); LQ.front->data = -1; LQ.front->next = NULL; LQ.rear = LQ.front; //隊首結點和隊尾結點是同一個結點 return LQ; } //遍歷打印出棧中的全部元素 void showStack(node* LS) { printf("鏈棧中的元素是:\n"); node* tmp; for (tmp = LS; tmp != NULL; tmp = tmp->next) { //遍歷時,注意tmp!=NULL,不是 tmp->next!=NULL,前者可以遍歷到棧底結點,后者棧底結點遍歷不到 printf("%d ", tmp->data); } printf("\n"); } //進棧 node* PushStack(node* LS ,int elem) { //LS是棧頂結點 node* new_node = (node*)malloc(sizeof(node)); //創建一個結點 if (new_node == NULL) { printf("創建鏈棧結點失敗\n"); exit(0); } else { new_node->data = elem; new_node->next = LS; //給新結點的指針域賦值,新結點指向當前棧頂結點 LS = new_node; //新結點成為新的棧頂結點 //printf("將%d壓入鏈棧后,棧頂元素是:%d\n", i, LS2->data); } return LS; } //出棧 void PopStack(node* LS) { while (LS != NULL) { node* tmp = LS; LS = tmp->next; printf("出棧元素是:%d\n", tmp->data); free(tmp); printf("棧頂元素是:%d\n", LS->data); } } //入隊列 LQ pushQueue(LQ LQ) { for (int i = 1; i < 10; i++) { node* new_node = (node*)malloc(sizeof(node));//生成新結點 new_node->data = i; new_node->next = NULL; LQ.rear->next = new_node; //在隊尾結點處插入新結點 LQ.rear = new_node;//隊尾結點后移 } return LQ; } //出隊列 node* popQueue(LQ LQ,node* LS) { while (LQ.front != LQ.rear) { printf("出隊結點是:%d\n", LQ.front->next->data); //從入隊第一個元素開始打印 LS = PushStack(LS, LQ.front->next->data); //出隊元素進棧 showStack(LS); //PopStack(LS); node* tmp = LQ.front; LQ.front = LQ.front->next; free(tmp); } free(LQ.front); return LS; } //打印隊列全部元素 void showLQ(LQ LQ) { node* tmp = LQ.front; while (tmp != NULL) { printf("%d ", tmp->data); tmp = tmp->next; } printf("\n"); } void main() { struct LinkQueue myLQ; node* mystack = NULL; myLQ.front = myLQ.rear = NULL; myLQ = initLQ(myLQ); printf("初始化空隊列是:\n"); printf("%d\n", myLQ.front->data); printf("隊首結點是:%d\n", myLQ.front->data); printf("隊尾結點是:%d\n", myLQ.rear->data); myLQ = pushQueue(myLQ); printf("將1-9個元素入隊后的隊列是:\n"); showLQ(myLQ); printf("隊首結點是:%d\n", myLQ.front->data); printf("隊尾結點是:%d\n", myLQ.rear->data); printf("鏈隊列元素開始出隊:\n"); mystack=popQueue(myLQ,mystack); printf("隊列元素出隊列后,進棧,再出棧:\n"); PopStack(mystack); }