在计算机考研数据结构领域,代码题是检验考生算法设计与实现能力的重要环节。以下是一道典型的数据结构代码题:
题目:实现一个单链表,支持以下操作:
1. 创建链表
2. 插入节点
3. 删除节点
4. 查找节点
5. 打印链表
要求:
- 使用C语言实现
- 链表节点包含数据域和指针域
- 插入和删除操作需保证链表元素的逻辑顺序
代码示例:
```c
include
include
typedef struct Node {
int data;
struct Node* next;
} Node;
// 创建链表
Node* createList() {
Node* head = (Node*)malloc(sizeof(Node));
head->next = NULL;
return head;
}
// 插入节点
void insertNode(Node* head, int data) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->next = head->next;
head->next = newNode;
}
// 删除节点
void deleteNode(Node* head, int data) {
Node* temp = head;
while (temp->next != NULL && temp->next->data != data) {
temp = temp->next;
}
if (temp->next != NULL) {
Node* delNode = temp->next;
temp->next = delNode->next;
free(delNode);
}
}
// 查找节点
Node* findNode(Node* head, int data) {
Node* temp = head->next;
while (temp != NULL && temp->data != data) {
temp = temp->next;
}
return temp;
}
// 打印链表
void printList(Node* head) {
Node* temp = head->next;
while (temp != NULL) {
printf("%d ", temp->data);
temp = temp->next;
}
printf("\n");
}
int main() {
Node* head = createList();
insertNode(head, 1);
insertNode(head, 2);
insertNode(head, 3);
printList(head);
deleteNode(head, 2);
printList(head);
Node* node = findNode(head, 3);
if (node != NULL) {
printf("Node found with data: %d\n", node->data);
} else {
printf("Node not found.\n");
}
return 0;
}
```
总结:以上代码实现了单链表的基本操作,包括创建、插入、删除、查找和打印链表。通过这道题目,考生可以巩固对链表数据结构的理解和应用。
【考研刷题通】微信小程序,涵盖政治、英语、数学等全部考研科目,助你高效刷题,备战考研!快来体验吧!