用链表输出数组num[]={1,2,3,4}
时间: 2023-11-19 18:40:18 浏览: 141
可以使用链表来输出数组 `num[]={1,2,3,4}`,以下是一个示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义链表节点
struct Node {
int data;
struct Node* next;
};
// 将数组转换为链表
struct Node* arrayToLinkedList(int arr[], int size) {
struct Node* head = NULL;
struct Node* temp = NULL;
struct Node* current = NULL;
for (int i = 0; i < size; i++) {
temp = (struct Node*)malloc(sizeof(struct Node));
temp->data = arr[i];
temp->next = NULL;
if (head == NULL) {
head = temp;
} else {
current = head;
while (current->next != NULL) {
current = current->next;
}
current->next = temp;
}
}
return head;
}
// 打印链表元素
void printLinkedList(struct Node* head) {
struct Node* current = head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}
int main() {
int num[] = {1, 2, 3, 4};
int size = sizeof(num) / sizeof(num[0]);
// 将数组转换为链表
struct Node* head = arrayToLinkedList(num, size);
// 打印链表元素
printLinkedList(head);
return 0;
}
```
输出结果:
```
1 2 3 4
```
以上代码将数组 `num` 转换为链表,并按顺序打印链表的元素。
阅读全文