面试题答案
一键面试#include <stdio.h>
#include <stdlib.h>
// 定义结构体
struct Node {
int data;
struct Node *next;
};
// 创建新节点的函数
struct Node* createNode(int value) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
if (newNode == NULL) {
return NULL;
}
newNode->data = value;
newNode->next = NULL;
return newNode;
}
// 遍历链表的函数
void traverseList(struct Node* head) {
struct Node* current = head;
while (current != NULL) {
if (current->next == NULL) {
printf("到达链表末尾\n");
}
current = current->next;
}
printf("链表遍历结束\n");
}
你可以使用以下方式调用这些函数:
int main() {
// 创建链表
struct Node* head = createNode(1);
struct Node* node2 = createNode(2);
struct Node* node3 = createNode(3);
head->next = node2;
node2->next = node3;
// 遍历链表
traverseList(head);
// 释放链表内存(这里省略具体释放代码)
return 0;
}