链表的合并与反转

将两个递增的链表合并为一个递增的链表,然后将这个链表反转


第一行输入一个数n,第二行输入n个递增的数,第三行输入m,再输入m个数,最后输出这n+m个数的递增的链表与递减的

代码如下:


#include <iostream>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <cstring>
#include <map>
#include <cmath>
#include <string>
#include <queue>
#include <stack>
#include <math.h>

using namespace std;

const int N = 905;

typedef struct LNode
{
	double data;
	LNode *next;
}LNode, *LinkList;

//LinkList p;

void InitList(LinkList L)
{
	L = new struct LNode;
	L->next = NULL;
}

void InitList( LinkList L,int n,double an[])
{
	LinkList p, s;
	L->next = NULL;
//	L = new struct LNode;
	p = L;
	for (int i = 1; i <= n; i++)
	{
		s = new LNode;
		s->data = an[i];
		p->next = s;
		p = s;
		p->next = NULL;
	}
}



void ListInsert(LinkList &L, int i, double e)
{
	LinkList p, s;
	int j;
	p = L;
	j = 0;
	while (p && (j < i-1 ))
	{
		p = p->next; 
		j++;
	}
	if (!p || j > i - 1)
		return;//ERROR;
	s = new LNode;
	s->data = e;
	s->next = p->next;
	p->next = s;
	return;//OK


}

void printf(LinkList L)
{
	LinkList p1;
	p1 = L;
	while ( p1->next!=NULL)
	{
		p1 = p1->next;
		cout << p1->data << " ";
	}
	cout << endl;
}

void hebin(LinkList L1, LinkList L2)
{
	LinkList p1, p2;
	p1 = L1->next;
	p2 = L2->next;
	int i;
	i = 1;
	while ( p2 != NULL)
	{
		p1 = L1->next;
		i = 1;
		while (p1 != NULL&&p1->data < p2->data&&p1 != NULL)
		{
			i++;
			p1 = p1->next;
		}
		ListInsert(L1, i, p2->data);
		p2 = p2->next;
	}
}


void nizhuan(LinkList L1, LinkList L2)
{
	if (L1->next == NULL)
	{
		L2->next = L1;
		return;
	}
	nizhuan(L1->next,L2);
	(L1->next)->next = L1;
	L1->next = NULL;
	return;
}


int main()
{
	double an[5000];
	int n;
	int i;
	double a;
	LinkList L1, L2, L3;
	L1 = new LNode;
	L2 = new LNode;
	L3 = new LNode;
	while (cin >> n)
	{
		for (i = 1; i <= n; i++)
		{
			cin >> an[i];
		}
		InitList(L1, n, an);
		cin >> n;
		for (i = 1; i <= n; i++)
		{
			cin >> an[i];
		}
		InitList(L2, n, an);


//		cout << L1->data << endl;

		printf(L1);
		printf(L2);

//		cout << "0asd\n";

		hebin(L1, L2);

//		cout << "1asd\n";

		printf(L1);

		nizhuan(L1->next, L1);

		printf(L1);

	}


	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值