代码: 全选
// special line structure | queue
// linked storage form
// Last Modified: 2008-07-07
#include <stdio.h>
#include <lee/stdiol.h>
#include <stdlib.h>
typedef struct node
{
int data;
struct node *next;
} node;
typedef struct
{
node *front;
node *rear;
} queue;
void enqueue(queue *q)
{
node *tmp = (node *)malloc(sizeof(node));
if (NULL == tmp)
{
perror("malloc");
return;
}
tmp->next = NULL;
printf("\n data: ");
tmp->data = getchar();
flush();
q->rear->next = tmp;
q->rear = tmp;
// free(tmp);
}
void dequeue(queue *q)
{
node *tmp;
if (q->front == q->rear)
{
printf("\n empty ");
return;
}
tmp = (node *)malloc(sizeof(node));
if (NULL == tmp)
{
perror("malloc");
return;
}
tmp = q->front->next;
q->front->next = tmp->next;
if (q->rear == tmp)
q->rear = q->front;
free(tmp);
}
void get_head(queue *q)
{
if (q->front == q->rear)
{
printf("\n empty ");
return;
}
printf("\n Queue Head: %c ", q->front->next->data);
}
void print(queue *q)
{
node *tmp;
if (q->front == q->rear)
{
printf("\n empty ");
return;
}
tmp = (node *)malloc(sizeof(node));
tmp = q->front;
printf("\n");
while (tmp != q->rear)
{
tmp = tmp->next;
printf(" | %c", tmp->data);
}
printf(" |");
}
int main()
{
// void create(queue *q);
void enqueue(queue *q);
void print(queue *q);
void get_head(queue *q);
int key;
queue *q;
node *n;
q = (queue *)malloc(sizeof(queue));
n = (node *)malloc(sizeof(node));
printf("\n");
printf("\n Special Line Structure | Queue - Linked Storage Form ");
printf("\n");
printf("\n init ... ");
q->front = q->rear = n;
while (1)
{
printf("\n");
printf("\n 1. create ");
printf("\n");
printf("\n 2. enqueue ");
printf("\n 3. dequeue ");
printf("\n 4. get head ");
printf("\n");
printf("\n 5. print ");
printf("\n");
printf("\n 0|q quit ");
printf("\n");
printf("\n ");
key = getchar();
flush();
switch (key)
{
case '1':
printf("\n\n continue ");
getch();
break;
case '2':
printf("\n");
printf("\n enqueue ");
printf("\n");
enqueue(q);
printf("\n\n continue ");
getch();
break;
case '3':
printf("\n");
printf("\n dequeue ");
printf("\n");
dequeue(q);
printf("\n\n continue ");
getch();
break;
case '4':
printf("\n");
printf("\n get head ");
printf("\n");
get_head(q);
printf("\n\n continue ");
getch();
break;
case '5':
printf("\n");
printf("\n print ");
printf("\n");
print(q);
printf("\n\n continue ");
getch();
break;
case 'q':
case '0':
goto QUIT_FLAG;
}
}
QUIT_FLAG:
return 0;
}
代码: 全选
#ifndef __STDIOL_H__
#define __STDIOL_H__
#include <stdio.h>
#include <stdlib.h>
int getch(void)
{
int key;
system("stty raw");
// stty - change and print terminal line settings
// raw - same as -ignbrk -brkint -ignpar -parmrk -inpck -istrip -inlcr
key = getchar();
system("stty cooked");
// cooked - same as brkint ignpar istrip icrnl ixon opost isig icanon,
// eof and eol characters to their default values
return key;
}
void flush()
{
int c;
while ((c = getchar() != '\n') && c != EOF) ;
}
#endif