链表编程题
编程求链表节点中的值是偶数的节点的值和。
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
int n;
const int maxn=1000;
struct node
{
int data;
node *next;
} ;
node* create(int a[],node *head)
{
node *pre,*p;
head->next=NULL;
pre=head;
for(int i=0;i<n;i++)
{
p=new node;
p->data=a[i];
p->next=NULL;
pre->next=p;
pre=p;
}
return head;
}
void print(node *head)
{
node *p=head->next;
while(p)
{
printf("%d ",p->data);
p=p->next;
}
printf("\n");
}
int Linksum(node *head)
{
node *p;
int sum=0;
p=head->next;
head->next=NULL;
while(p)
{
if(p->data%2==0)
{
sum=sum+p->data;
}
p=p->next;
}
return sum;
}
int main()
{
int a[maxn];
cin>>n;
int sum;
for(int i=0;i<n;i++)
{
cin>>a[i];
}
node *head=new node;
head->next=NULL;
cout<<"创建的链表如下:"<<endl;
head=create(a,head);
print(head);
sum= Linksum(head);
cout<<sum<<endl;
return 0;
}
然后输入 数字 1 2 3 4
可以得出结果6