请你用C语言写一段单链表的显示输出列表函数
时间: 2024-04-30 15:24:18 浏览: 10
好的,以下是用C语言写的单链表的显示输出列表函数:
```
void displayList(struct node *head) {
struct node *current = head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}
```
其中,`struct node`表示单链表节点的结构体,包括`int data`表示节点存储的数据,`struct node *next`表示指向下一个节点的指针。`head`表示单链表的头节点,即第一个节点。函数中使用`current`指针遍历单链表,输出每个节点的数据,直到遍历到链表尾部为止。
相关问题
请你用C语言写一段单链表的插入
好的,以下是用C语言实现单链表的插入代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义链表节点结构体
struct ListNode {
int val;
struct ListNode *next;
};
// 插入节点函数
void insertNode(struct ListNode **head, int val) {
struct ListNode *newNode = (struct ListNode*)malloc(sizeof(struct ListNode));
newNode->val = val;
newNode->next = NULL;
if (*head == NULL) {
*head = newNode;
return;
}
struct ListNode *cur = *head;
while (cur->next != NULL) {
cur = cur->next;
}
cur->next = newNode;
}
// 遍历链表函数
void traverseList(struct ListNode *head) {
if (head == NULL) {
printf("链表为空\n");
return;
}
printf("链表节点:");
while (head != NULL) {
printf("%d ", head->val);
head = head->next;
}
printf("\n");
}
int main() {
// 初始化链表头节点
struct ListNode *head = NULL;
// 插入节点
insertNode(&head, 1);
insertNode(&head, 2);
insertNode(&head, 3);
// 遍历链表
traverseList(head);
return 0;
}
```
以上代码实现了单链表的插入和遍历功能,可以根据需要进行修改和使用。
用c语言写一个单链表并输出单链表
以下是用 C 语言编写单链表并输出的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义单链表结构体
typedef struct ListNode {
int val;
struct ListNode *next;
} ListNode;
// 创建新节点
ListNode* createNode(int val) {
ListNode *node = (ListNode*)malloc(sizeof(ListNode));
node->val = val;
node->next = NULL;
return node;
}
// 插入节点到链表尾部
void insertNode(ListNode **head, int val) {
ListNode *node = createNode(val);
if (*head == NULL) {
*head = node;
return;
}
ListNode *cur = *head;
while (cur->next != NULL) {
cur = cur->next;
}
cur->next = node;
}
// 输出链表
void printList(ListNode *head) {
ListNode *cur = head;
while (cur != NULL) {
printf("%d ", cur->val);
cur = cur->next;
}
printf("\n");
}
int main() {
ListNode *head = NULL;
insertNode(&head, 1);
insertNode(&head, 2);
insertNode(&head, 3);
printList(head);
return 0;
}
```
输出结果为:
```
1 2 3
```
希望能对您有所帮助!