2016-06-24 240 views
-4

所以我明天要考试在Java中,并有队列的这个代码,我不明白,这是满级:我不明白这段代码是如何工作的?

public class queues { 

    static final int max = 5; 
    static int[] queue = new int[max]; 
    static int t = 0, h = 0; 

    static boolean isempty() { 
     return t == h; 
    } 

    static boolean isfull() { 
     return (t + 1) % max == h; 
    } 

    static void enqueue(int e) { 
     if (isfull()) { 
      System.out.println("Queue is Full"); 
     } else { 
      queue[t] = e; 
      t = (t + 1) % max; 
     } 
    } 

    static int dequeue() { 
     if (isempty()) { 
      System.out.println("Queue is empty"); 
      return 0; 
     } else { 
      int temp = queue[h]; 
      queue[h] = 0; 
      h = (h + 1) % max; 
      return temp; 
     } 
    } 
} 

但我不明白的是enqueue()时方法否则执行..不应t=(t+1)%max;之前queue[t]=e;, 或不应该我们写queue[t=(t+1)%max]=e而不是?因为我们在t的旁边插入一个元素,而不是t本身。 有人可以向我解释这个插入是如何工作的吗?

+0

按照命名规则和格式化你的代码。 – eldo

+0

如果你是初学者,不要试图从代码学习概念。首先了解队列的工作原理和基本操作。然后尝试自行编码。祝你好运! – uniquephase

+0

只需通过空队列的代码,你实际上插入't'! – luk2302

回答

1

考虑队列是空的,所以你的t == 0.当你用enqueue方法插入第一个元素时,它应该放在int []队列数组的0位置。然后你的指针增加,这样下一次元素将被插入到1的位置。因此,首先插入完成,然后你的指针增加,但反之亦然。

所以,基本上,你的T只是一个指向小区的新元素应该插入的一个指针。

相关问题