#include<stdio.h>
#include<stdlib.h>
#define LEN sizeof(struct node)
struct node{
int data;
struct node *next;
};
int main(){
struct node *head=NULL,*p,*q;
int i,n=5;
for(i=1;i<=n;i++){
p=(struct node*)malloc(LEN);
printf("请输入第%d个节点的数据:",i);
scanf("%d",&p->data);
p->next=NULL;
if(head==NULL)
head=p;
else{
q=head;
while(q->next!=NULL)
q=q->next;
q->next=p;
}
}
p=head;
while(p!=NULL){
if(p->next!=NULL){
q=p->next;
p->data=p->data+q->data;
p->next=q->next;
free(q);
}
p=p->next;
}
p=head;
do{
printf("%d",p->data);
p=p->next;
}while(p!=NULL);
return 0;
}
#include <iostream>
using namespace std;
struct node{
int data;
struct node *next;
};
node* creat() {
node * h, * p, * q;
int ch;
h = new node;
p = q = h;
cout<<"请输入结点数据:";
cin >> ch;
cout<<endl;
while (ch != -1)
{
p = new node;
p->data = ch;
q->next = p;
q = p;
cout<<"请输入结点数据:";
cin >> ch;
cout<<endl;
}
p->next = NULL;
return h;
}
void print(node* head) {
node* p;
p = head->next;
cout<<"结果为:";
if (p != NULL) {
while (p != NULL) {
cout << p->data<<"\t";
p = p->next;
}
cout<<endl;
}
}
void merge(node *h)
{
node *p1,*p2;
if(h==NULL)
return;
p1=h->next;
p2=p1->next;
while(p2){
p1->data +=p2->data;
p1->next=p2->next;
delete p2;
p1= p1->next;
if( p1!=0&&p1->next)
p2=p1->next;
else
p2=NULL;
}
return;
}
int main(){
node* h = creat();
merge(h);
print(h);
}