【数据结构】——链式队列操作
1 #include<stdio.h> 2 #include<string.h> 3 #include<stdlib.h> 4 5 typedef struct node 6 { 7 int item; 8 struct node *next; 9 }node; 10 11 typedef struct queue 12 { 13 node *front; 14 node *rear; 15 }queue; 16 17 char getfirst() 18 { 19 char value; 20 value = getchar(); 21 while(value == '\n' || value == '\t') 22 { 23 value = getchar(); 24 while(getchar() != '\n'); //去掉多余的输入 25 } 26 while(getchar() != '\n'); //如果第一次输入正确,则去掉最后一个换行符; 27 return value; 28 } 29 30 int getint() 31 { 32 int value; 33 while(scanf("%d",&value) != 1) 34 { 35 printf("请输入数字;\n"); 36 while(getchar() != '\n'); 37 } 38 while(getchar() != '\n'); 39 return value; 40 } 41 42 int menu() 43 { 44 int value; 45 printf("*************************************\n"); 46 printf("一:入队列;\n"); 47 printf("二:出队列;\n"); 48 printf("*************************************\n"); 49 value = getint(); 50 while(value > 2 || value < 1) 51 { 52 printf("请输入1-2:\n"); 53 value = getint(); 54 } 55 return value; 56 } 57 58 queue *init() 59 { 60 queue *h; 61 node *n; 62 n = (node *)malloc(sizeof(node)); 63 h = (queue *)malloc(sizeof(queue)); 64 65 n->item = 0; 66 n->next = NULL; 67 68 h->front = n; 69 h->rear = n; 70 return h; 71 } 72 73 void pop(queue *h, int item_value) //入队列 头指针指向第一个元素,尾指针指向最后一个空元素 74 { 75 node *value; 76 value = (node *)malloc(sizeof(node)); 77 78 h->rear->item = item_value; 79 80 value->item = 0; 81 value->next = NULL; 82 83 h->rear->next = value; 84 h->rear = value; 85 } 86 87 void push(queue *h) //出队列 88 { 89 if(h->rear == h->front) 90 { 91 printf("队列已经没有数据!"); 92 } 93 else 94 { 95 node *temp; 96 int value; 97 temp = h->front; 98 h->front = h->front->next; 99 value = temp->item; 100 free(temp); 101 printf("%d\t",value); 102 } 103 104 } 105 106 void queue_out(queue *h) 107 { 108 char value; 109 do 110 { 111 push(h); 112 puts("countine?(y/n)"); 113 value = getfirst(); 114 while(value != 'y' && value != 'Y' && value != 'n' && value != 'N') 115 { 116 printf("请输入(y/n)\n"); 117 value = getfirst(); 118 } 119 }while(value == 'y' || value == 'Y'); 120 121 } 122 123 124 void queue_in(queue *h) 125 { 126 int value; 127 char ch; 128 do 129 { 130 value = getint(); 131 pop(h,value); 132 puts("countine?(y/n)"); 133 ch = getfirst(); 134 while(ch != 'y' && ch != 'Y' && ch != 'n' && ch != 'N') 135 { 136 printf("请输入(y/n)\n"); 137 ch = getfirst(); 138 } 139 }while(ch == 'y' || ch == 'Y'); 140 } 141 142 int main(void) 143 { 144 queue *h; 145 char value; 146 h = init(); 147 do 148 { 149 switch(menu()) 150 { 151 case 1:queue_in(h);break; 152 case 2:queue_out(h);break; 153 } 154 printf("是否需要继续?(y/n)\n"); 155 value = getfirst(); 156 while(value != 'y' && value != 'Y' && value != 'n' && value != 'N') 157 { 158 printf("请输入(y/n)\n"); 159 value = getfirst(); 160 } 161 }while(value == 'y' || value == 'Y'); 162 return 0; 163 }
队列的操作无非就是出队列,入队列;设计完队列的数据结构之后,就如同操作链表一样了;