给我一个能输出值的单链表c语言代码
时间: 2024-05-19 18:17:13 浏览: 10
以下是一个能输出值的单链表 C 语言代码:
#include <stdio.h>
#include <stdlib.h>
//定义链表的结构体
struct Node {
int data;
struct Node* next;
};
//函数:创建链表
void push(struct Node** head_ref, int new_data)
{
//申请新节点空间
struct Node* new_node = (struct Node*) malloc(sizeof(struct Node));
//给新节点赋值
new_node->data = new_data;
//使新节点成为头结点
new_node->next = (*head_ref);
//替换原来的头结点
(*head_ref) = new_node;
}
//函数:打印链表
void printList(struct Node* n)
{
while (n != NULL) {
printf("%d ", n->data);
n = n->next;
}
}
//主函数
int main()
{
//开始创建链表
struct Node* head = NULL;
//增加新节点
push(&head, 1);
push(&head, 2);
push(&head, 3);
push(&head, 4);
push(&head, 5);
//打印链表
printf("链表的值为:");
printList(head);
return 0;
}