c语言别踩白块中链表的定义与实现效果
时间: 2023-12-05 14:06:03 浏览: 37
链表是一种常用的数据结构,可以用于实现各种算法和数据结构。下面是一个使用链表实现别踩白块游戏的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
// 定义节点结构体
typedef struct Node {
int x; // x坐标
int y; // y坐标
struct Node *next; // 指向下一个节点的指针
} Node;
// 定义链表结构体
typedef struct List {
Node *head; // 链表头节点指针
Node *tail; // 链表尾节点指针
int length; // 链表长度
} List;
// 初始化链表
void initList(List *list) {
list->head = NULL;
list->tail = NULL;
list->length = 0;
}
// 创建新节点
Node *createNode(int x, int y) {
Node *node = (Node *)malloc(sizeof(Node));
node->x = x;
node->y = y;
node->next = NULL;
return node;
}
// 插入节点到链表尾部
void appendNode(List *list, Node *node) {
if (list->head == NULL) {
list->head = node;
list->tail = node;
} else {
list->tail->next = node;
list->tail = node;
}
list->length++;
}
// 从链表头部删除节点
void deleteHeadNode(List *list) {
if (list->head == NULL) {
return;
}
Node *node = list->head;
list->head = node->next;
free(node);
list->length--;
}
// 遍历链表并输出节点信息
void printList(List *list) {
Node *node = list->head;
while (node != NULL) {
printf("(%d, %d)\n", node->x, node->y);
node = node->next;
}
}
int main() {
srand(time(NULL));
List list;
initList(&list);
int x = 0, y = 0;
for (int i = 0; i < 10; i++) {
x += rand() % 3 - 1;
y += rand() % 3 - 1;
Node *node = createNode(x, y);
appendNode(&list, node);
}
printList(&list);
for (int i = 0; i < 5; i++) {
deleteHeadNode(&list);
}
printf("After delete head nodes:\n");
printList(&list);
return 0;
}
```
在这个示例代码中,我们首先定义了一个节点结构体`Node`,其中包含了节点的横纵坐标和指向下一个节点的指针。然后我们定义了一个链表结构体`List`,其中包含了链表的头节点指针、尾节点指针和长度。链表的初始化函数`initList`会将头尾指针和长度都初始化为0。创建新节点的函数`createNode`会根据传入的坐标信息创建一个新的节点,并返回节点指针。将节点插入到链表尾部的函数`appendNode`会根据链表是否为空来分别对头尾指针进行赋值,并将新节点插入到尾部。从链表头部删除节点的函数`deleteHeadNode`会先判断链表是否为空,如果不为空则将头节点指针指向下一个节点,并释放头节点的内存,同时将长度减1。遍历链表并输出节点信息的函数`printList`会从头节点开始遍历链表,并输出每个节点的坐标信息。
在`main`函数中,我们使用随机数生成了10个坐标信息,并将其插入到链表中。然后我们调用`printList`函数来输出链表中的所有节点信息。接着我们用循环删除了前5个节点,并再次调用`printList`函数来验证链表的删除操作是否成功。
本示例代码中的链表实现只是一个简单的示例,仅供参考。实际应用中可能需要根据具体需求对链表进行更加复杂的操作。