체인 테이블이 양단 대기열을 실현하다


  
  
  
  
  1. #include <stdio.h> 
  2. #include <stdlib.h> 
  3. typedef struct _queue 
  4. { 
  5.     int data; 
  6.     struct _queue *next; 
  7. }QUEUE; 
  8.  
  9. QUEUE *front = NULL, *rear = NULL; 
  10.  
  11. int InQueue(int value) 
  12. { 
  13.     QUEUE *temp = NULL; 
  14.      
  15.     temp = (QUEUE *)malloc(sizeof(QUEUE)); 
  16.     temp->data = value; 
  17.     temp->next = NULL; 
  18.  
  19.     if(front == NULL)    
  20.         front = temp; 
  21.     else  
  22.         rear->next = temp; 
  23.     rear = temp; 
  24.     return 1; 
  25. }                                //      
  26. int InQueue2(int value) 
  27. { 
  28.     QUEUE *temp = NULL; 
  29.     temp = (QUEUE *)malloc(sizeof(QUEUE)); 
  30.      
  31.     temp->data = value; 
  32.     temp->next =  NULL; 
  33.  
  34.     if(front == NULL && rear == NULL) 
  35.     { 
  36.         front = rear = temp; 
  37.         rear->next = front->next =  NULL; 
  38.     } 
  39.     else 
  40.     { 
  41.         temp->next = front; 
  42.         front = temp; 
  43.     } 
  44. }                        //    
  45.  
  46. int OutQueueByFront(int *value) 
  47. { 
  48.     QUEUE *temp = NULL; 
  49.     temp = front; 
  50.     if(front == NULL) 
  51.         return 0; 
  52.     *value = front->data; 
  53.     front = front->next; 
  54.     free(temp); 
  55.     return 1; 
  56. } 
  57.  
  58. int OutQueueByRear(int *value) 
  59. { 
  60.     QUEUE *temp; 
  61.     if(rear == NULL) 
  62.         return 0; 
  63.      
  64.     if(front == rear) 
  65.     { 
  66.         *value = rear->data; 
  67.         free(rear); 
  68.         front = NULL; 
  69.         rear = NULL; 
  70.     }else  
  71.     { 
  72.         temp = front; 
  73.         while(temp->next != rear) 
  74.             temp = temp->next; 
  75.         *value = rear->data; 
  76.         free(rear); 
  77.         rear = temp; 
  78.         rear->next = NULL; 
  79.     } 
  80.     return 1; 
  81. } 
  82.  
  83.  
  84. void main() 
  85. { 
  86.     int arr[6] = {1,2,3,4,5,6},res,i; 
  87.     for(i=0; i<6; i++) 
  88.         InQueue2(arr[i]); 
  89.     if(OutQueueByFront(&res)) 
  90.         printf("what we get is  %d  
    "
    ,res); 
  91.     else printf("we not get it
    "
    ); 
  92.         if(OutQueueByRear(&res)) 
  93.         printf("what we get is  %d  
    "
    ,res); 
  94.     else printf("we not get it
    "
    ); 
  95. } 

좋은 웹페이지 즐겨찾기