代码如下:
#define _CRT_SECURE_NO_WARNINGS 1
#include <iostream>
using namespace std;
#define maxSize 100
typedef struct LNode
{
int data;
struct LNode* next;
}LNode;
int main()
{
void createlistR(LNode*&, int[], int);
void printlist(LNode*);
LNode* C;
int a[maxSize], n;
cout << "Please enter the number of the elements: ";
cin >> n;
cout << "Please enter the elements one by one: ";
{
for (int i = 0; i < n; i++)
{
cin >> a[i];
}
}
createlistR(C, a, n);
printlist(C);
return 0;
}
void createlistR(LNode*& C, int a[], int n)
{
LNode* s, * r;
C = (LNode*)malloc(sizeof(LNode));
r = C;
for (int i = 0; i < n; i++)
{
s = (LNode*)malloc(sizeof(LNode));
s->data = a[i];
r->next = s;
r = r->next;
}
r->next = NULL;
return;
}
void printlist(LNode* C)
{
C = C->next;
while (C)
{
printf("%d", C->data);
if (C->next)
{
printf(" -> ");
}
C = C->next;
}
return;
}
该代码示例展示了如何使用C++创建一个单链表,并对其进行输入元素及打印操作。程序首先定义了一个链表节点结构体,然后在主函数中接收用户输入的元素数量及元素值,调用`createlistR`函数创建链表,最后通过`printlist`函数输出链表内容。
9784

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



