C语言用尾插法建立链表并输出
时间: 2023-05-23 17:00:56 浏览: 98
以下是用C语言实现用尾插法建立链表并输出的代码:
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int data;
struct node* next;
} Node;
Node* create_list(int n) {
Node* head = NULL, * tail = NULL;
int i, data;
for (i = 0; i < n; i++) {
printf("请输入第 %d 个节点的值: ", i + 1);
scanf("%d", &data);
Node* new_node = (Node*)malloc(sizeof(Node));
new_node->data = data;
new_node->next = NULL;
if (head == NULL) {
head = tail = new_node;
}
else {
tail->next = new_node;
tail = new_node;
}
}
return head;
}
void print_list(Node* head) {
Node* p = head;
printf("链表的值为: ");
while (p) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
int main() {
int n;
printf("请输入链表的长度: ");
scanf("%d", &n);
Node* head = create_list(n);
print_list(head);
return 0;
}
希望能帮到你!
阅读全文