使用鏈表實現多窗口佇列,隨機生成客戶到達與業務時間,時間推進模擬服務過程,展示離散事件模擬核心邏輯。
MAX_WIN = 20 服務窗口stay 剩餘服務時間stay--
typedef struct customer *Link;
struct customer {
int stay; // 剩餘服務時間
Link next; // 下一客戶
};
Link windows[MAX_WIN] = {NULL}; // 20個窗口佇列頭指針
void arrive(int w, int stay) {
Link c = malloc(sizeof(*c));
c->stay = stay;
if (windows[w] == NULL) {
windows[w] = c->next = c; // 循環鏈表單節點自環
} else {
c->next = windows[w]->next;
windows[w]->next = c;
windows[w] = c; // 尾指針後移
}
}
void depart(int w) {
Link head = windows[w];
if (head->next == head) { // 單節點
free(head);
windows[w] = NULL;
} else {
Link first = head->next;
head->next = first->next;
free(first);
}
}
void tick() {
for (int w = 0; w < MAX_WIN; w++) {
if (windows[w] == NULL) continue;
Link current = windows[w]->next; // 隊首
if (--current->stay <= 0)
depart(w);
}
}
void display() {
system("clear"); // Windows 用 cls
for (int w = 0; w < MAX_WIN; w++) {
printf("WIN%3d: ", w);
if (windows[w] == NULL) { printf("\n"); continue; }
Link p = windows[w]->next;
do {
printf("%4d", p->stay);
p = p->next;
} while (p != windows[w]->next);
printf("\n");
}
Sleep(100); // 100ms/步
}
int main() {
srand(time(NULL));
for (init(); ; tick()) {
arrive(rand()%MAX_WIN, rand()%100+1); // 隨機到達
display();
}
}
銀行排隊模擬是離散事件模擬教學經典案例,C 語言實現鍛鍊指針、鏈表、隨機數、終端控制綜合能力。