2620: B 链表操作
Description
(1)编写一个函数createlink,用来建立一个动态链表(链表中的节点个数由参数count来控制)。
节点结构如下:
struct Node
{
int data;
Node * next;
};
函数createlink的声明如下:
Node * createlink(int count);
(2)编写一个函数printlink,用来遍历输出一个链表。
函数printlink的声明如下:
void printlink(Node * head);
(3) 在主程序中调用函数createlink来动态创建链表,然后调用printlink函数遍历输出链表节点数据。
主程序如下:(提交时不用提交主程序)
int main()
{
Node * head=NULL;
int n;
cin>>n;
head=createlink(n);
printlink(head);
return 0;
}
Input
输入要建立链表的节点个数
输入各个节点的数据
Output
输出链表中各个节点的数据
Sample Input
4
1 2 3 4
Sample Output
1 2 3 4
HINT
提交时不用提交主程序,其他都要提交
#include<iostream> #include<cstdio> using namespace std; struct Node { int data; Node * next; }; int main() { Node * createlink(int count); void printlink(Node * head); Node * head=NULL; int n; cin>>n; head=createlink(n); printlink(head); return 0; } Node * createlink(int count) { Node *p,*s,*r; int n,m,i; Node *L = new Node; scanf("%d",&m); L->data=m; p=L; r=L; for(i=0;i<count-1;i++) { cin>>n; Node *p = new Node; p->data=n; r->next=p; r=p; } r->next=NULL; return L; } void printlink(Node * head) { while(head!=NULL) { printf("%d ",head->data); head=head->next; } }