用c语言创建一个单链表并运行出来
时间: 2023-03-29 19:00:44 浏览: 125
可以使用C语言的结构体来创建单链表,具体步骤如下:
1. 定义一个结构体,包含一个数据域和一个指向下一个节点的指针域。
```
struct Node {
int data;
struct Node* next;
};
```
2. 创建一个头节点,并将其指针域置为NULL。
```
struct Node* head = NULL;
```
3. 定义一个函数,用于在链表末尾添加节点。
```
void append(int data) {
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
new_node->data = data;
new_node->next = NULL;
if (head == NULL) {
head = new_node;
return;
}
struct Node* current = head;
while (current->next != NULL) {
current = current->next;
}
current->next = new_node;
}
```
4. 在主函数中调用append函数,添加节点并输出链表中的所有元素。
```
int main() {
append(1);
append(2);
append(3);
struct Node* current = head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
return ;
}
```
输出结果为:1 2 3
注意:以上代码仅为示例,实际应用中需要根据具体需求进行修改和完善。
阅读全文
相关推荐
















