用C语言写个单链表
时间: 2024-02-10 18:10:35 浏览: 18
以下是用C语言实现单链表的基本代码:
```
#include<stdio.h>
#include<stdlib.h>
struct node{
int data;
struct node *next;
};
struct node *create_list(int n){
struct node *head = NULL;
struct node *temp = NULL;
struct node *p = NULL;
int i;
for(i=0; i<n; i++){
temp = (struct node *)malloc(sizeof(struct node));
printf("请输入第%d个节点的值: ", i+1);
scanf("%d", &temp->data);
temp->next = NULL;
if(head == NULL){
head = temp;
}else{
p = head;
while(p->next != NULL){
p = p->next;
}
p->next = temp;
}
}
return head;
}
void print_list(struct node *head){
struct node *p = head;
while(p != NULL){
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
int main(){
int n;
struct node *head = NULL;
printf("请输入链表长度: ");
scanf("%d", &n);
head = create_list(n);
printf("链表为: ");
print_list(head);
return 0;
}
```
上述代码实现了单链表的创建和打印功能。其中,结构体`node`表示链表的节点,包含一个数据域`data`和一个指向下一个节点的指针`next`。`create_list`函数用于创建链表,其参数`n`表示链表长度,返回值为链表的头节点。`print_list`函数用于打印链表,其参数为链表的头节点。在`main`函数中,用户需要输入链表的长度,然后调用`create_list`函数创建链表,最后调用`print_list`函数打印链表。