c语言利用循环向单链表尾插五个元素,并输出
时间: 2023-04-10 10:01:26 浏览: 90
单链表建立尾接法(C语言源代码)
可以回答这个问题。以下是示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
int main() {
struct Node* head = NULL;
struct Node* tail = NULL;
int i;
for (i = 0; i < 5; i++) {
struct Node* newNode = (struct Node*) malloc(sizeof(struct Node));
newNode->data = i;
newNode->next = NULL;
if (tail == NULL) {
head = newNode;
tail = newNode;
} else {
tail->next = newNode;
tail = newNode;
}
}
struct Node* current = head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
return 0;
}
```
这段代码利用循环向单链表尾插入五个元素,并输出它们的值。
阅读全文