这段代码是用来创建一个单链表的函数。具体实现如下:
#include <stdio.h>
#include <stdlib.h>
struct ListNode {
char val;
struct ListNode* next;
};
struct ListNode* createlink(int n) {
struct ListNode* head, * node, * end;
head = (struct ListNode*)malloc(sizeof(struct ListNode));
if (head == NULL) {
printf("内存分配失败\n");
exit(1);
}
end = head; // 空链表的头节点就是尾结点
for (int i = 0; i < n; i++) {
node = (struct ListNode*)malloc(sizeof(struct ListNode));
if (node == NULL) {
printf("内存分配失败\n");
exit(1);
}
getchar(); // 处理换行符
scanf("%c", &node->val);
end->next = node;
end = node;
}
end->next = NULL; // 尾结点指空
return head->next; // 消除头节点,返回的头指针直接指向首节点
}
int main() {
int n;
printf("请输入链表节点个数: ");
scanf("%d", &n);
struct ListNode* head = createlink(n);
printf("链表内容为: ");
struct ListNode* cur = head;
while (cur != NULL) {
printf("%c ", cur->val);
cur = cur->next;
}
return 0;
}
这段代码会根据输入的节点个数和每个节点的值来创建一个单链表,并输出链表内容。注意,在使用之前需要包含 <stdio.h>
和 <stdlib.h>
头文件。
内容由零声教学AI助手提供,问题来源于学员提问