使用c语言链表实现的简单祖玛游戏代码
时间: 2023-09-28 12:13:14 浏览: 59
好的,以下是一个简单的使用 C 语言链表实现的祖玛游戏代码示例,供您参考:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
// 定义链表节点
typedef struct node {
int val;
struct node* next;
} Node;
// 初始化链表
Node* initList() {
Node* head = (Node*)malloc(sizeof(Node));
head->val = -1;
head->next = NULL;
return head;
}
// 生成随机的祖玛球
int getRandBall() {
return rand() % 4 + 1;
}
// 向链表中插入节点
void insert(Node* head, int val) {
Node* node = (Node*)malloc(sizeof(Node));
node->val = val;
node->next = NULL;
Node* p = head;
while (p->next != NULL) {
p = p->next;
}
p->next = node;
}
// 打印链表
void printList(Node* head) {
Node* p = head->next;
while (p != NULL) {
printf("%d ", p->val);
p = p->next;
}
printf("\n");
}
// 删除链表中的连续球
void removeBalls(Node* head) {
Node* p = head->next;
Node* q = p;
int cnt = 1;
while (p->next != NULL) {
if (p->val == p->next->val) {
cnt++;
} else {
if (cnt >= 3) {
while (cnt--) {
Node* tmp = q;
q = q->next;
free(tmp);
}
head->next = q;
p = q;
cnt = 1;
} else {
q = p->next;
cnt = 1;
p = p->next;
}
}
}
if (cnt >= 3) {
while (cnt--) {
Node* tmp = q;
q = q->next;
free(tmp);
}
head->next = q;
}
}
// 主函数
int main() {
srand(time(NULL));
Node* head = initList();
for (int i = 0; i < 10; i++) {
insert(head, getRandBall());
}
printf("初始球序列:");
printList(head);
removeBalls(head);
printf("删除连续球后的球序列:");
printList(head);
return 0;
}
```
上述代码实现了一个简单的祖玛游戏,通过链表来存储祖玛球序列,并在其中删除连续的相同球。您可以根据需要进行修改和扩展。