题目:传入一个数组,以链表的形式输出。
参考代码一:
#include <iostream>
#include <memory>
#include <malloc.h>
#include <stdlib.h>
using namespace std;
typedef struct Node
{
int value;
Node *next;
}Node;
Node *create_node(int *arr, int n)
{
Node *head = new Node();
Node *cur = head;
for (int i = 0; i < n; i++)
{
cur->next = new Node();
cur = cur->next;
cur->value = arr[i];
}
return head->next;
}
void show(Node *head)
{
while (head != NULL)
{
cout <<"data = " << head->value << endl;
head = head->next;
}
}
int main()
{
int a[] = {10, 20, 50, 70, 90};
Node *head = create_node(a, 5);
show(head);
return 0;
}
//输出
data = 10
data = 20
data = 50
data = 70
data = 90
参考代码二:
#include <iostream>
#include <memory>
#include <malloc.h>
#include <stdlib.h>
using namespace std;
typedef struct Node
{
int value;
Node *next;
}Node;
Node *create_node(int *arr, int n)
{
Node *head = (Node *)malloc(sizeof(struct Node));
Node *pre = head;
Node *cur = NULL;
for (int i = 0; i < 3; i++)
{
cur = (Node *)malloc(sizeof(struct Node));
cur->value = arr[i];
pre->next = cur;
pre = pre->next;
}
pre->next = NULL;
return head->next;
}
void show(Node *head)
{
while (head)
{
int data = head->value;
cout << "data = " << data << endl;
head = head->next;
}
}
int main()
{
int a[] = {10, 20, 50};
Node *head = create_node(a, 3);
show(head);
return 0;
}
//输出
data = 10
data = 20
data = 50
参考代码三:
#include <stdio.h>
#include <malloc.h>
#include <iostream>
using namespace std;
struct Node {
int val;
Node* next;
};
Node* arrayToList(int* arr, int n) {
if (n <= 0) return NULL;
Node* head = new Node();
Node* curr = head;
for (int i = 0; i < n; ++i) {
curr->next = new Node();
curr = curr->next;
curr->val = arr[i];
}
return head->next;
}
void printList(Node* head) {
while (head != NULL) {
cout << head->val << " ";
head = head->next;
}
cout << endl;
}
int main() {
int arr[] = {10, 20, 30, 40, 50};
Node* head = arrayToList(arr, 5);
printList(head);
return 0;
}
//输出
10 20 30 40 50
参考代码四:
#include <stdio.h>
#include <malloc.h>
#include <iostream>
using namespace std;
typedef struct Node
{
int data;
struct Node* next; //指向后继结点
}LinkNode; //声明单链表结点类型
// 尾插法建立单链表
void CreateList(LinkNode*& head, int a[], int n)
{
struct Node *cur, *pre;
head = (LinkNode*)malloc(sizeof(struct Node));
head->next = NULL;
pre = head;
for (int i = 0; i < n; i++)
{
cur = (LinkNode*)malloc(sizeof(struct Node));
cur->data = a[i];
pre->next = cur;
pre = cur;
}
pre->next = NULL;
}
// 输出链表中的数据
void DispList(LinkNode* L)
{
struct Node* p = L->next;
while (p != NULL)
{
printf("%d ", p->data);
p = p->next;
}
}
int main()
{
int i = 0, n;
cout << "请输入数组元素的个数:" <<endl;
scanf("%d", &n);
int a[100];
cout << "输入数组元素:" <<endl;
for (i = 0; i < n; i++)
{
scanf("%d", &a[i]);
}
LinkNode* head;
CreateList(head, a, n);
cout << "输出链表: " <<endl;
DispList(head);
return 0;
}
//输出
请输入数组元素的个数:
3
输入数组元素:
11
22
33
输出链表:
11 22 33
4134

被折叠的 条评论
为什么被折叠?



