编程题 将一条链表上相邻的两个结点合并成一个结点,即将第1个结点与第2个结点合并,将第3个结点与第4个结点合并,……如果链表上结点个数为奇数,则最后一个结点不合并,直接作为合并后链表上的最后一个结点。

#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);
		//p1 = p2 = (struct student *)malloc(LEN); malloc分配空间,即分配LEN个字节的空间,
		// p1,p2为指针,他们这是指向的就是分配空间时分配的地址。
		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);

	

} 
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值