考研連結串列程式設計題求連結串列中的值是偶數的節點的和(2017華中師範大學874)
阿新 • • 發佈:2019-01-06
連結串列程式設計題
程式設計求連結串列節點中的值是偶數的節點的值和。
#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