24.链表的逆置与合并

题目:

1、对一个链表进行就地逆置

2、对两个有序链表进行合并,合并为一个有序链表

答案:

//20130130
#include <iostream>

using namespace std;
typedef struct node 
{
	int num;
	node* next;
}node,*pnode;

pnode makeList(const int s[],int n);
void printList(const pnode p);
int inverseList(const pnode p);
pnode mergeList(const pnode a, const pnode b);
int main()
{
	int a[10] = {10,20,30,40,50,60,70,80,90,100};
	int b[10] = {9,11,22,23,45,67,79,101,102,103};
	//链表就地逆置
	//生成链表,带表头
	pnode pn = makeList(a,10);
	printList(pn);
	int n=inverseList(pn);
	cout<<endl;
	printList(pn);
	cout<<endl;
	//两个链表合并,生成有序链表
	pnode p1 = makeList(a,10);
	pnode p2 = makeList(b,10);
	pnode p=mergeList(p1,p2);
	printList(p);
	return 0;
}
pnode makeList(const int s[], int n)
{
	pnode pre = NULL;
	pnode head=new node;
	head->num = -1;
	pre = head;
	for (int i = 0;i < n;i++)
	{
		pnode p=new node;
		p->num=s[i];

		pre->next = p;
		pre = p;
	}
	pre->next = NULL;
	return head;
}
int inverseList(const pnode p)
{
	pnode head = p->next;
	pnode now = head->next;
	head->next = NULL;
	pnode last = now->next;
	while (last != NULL)
	{
		now->next = head;
		head = now;
		now = last;
		last = last->next;
	}
	now->next = head;
	p->next = now;
	return 0;//返回0,表示成功
}
void printList(const pnode p)
{
	pnode tmp = p->next;
	while (tmp !=NULL)
	{
		cout<<tmp->num<<",";
		tmp = tmp->next;
	}
}
pnode mergeList(const pnode a, const pnode b)
{
	pnode head = new node;
	pnode p1 = a->next;
	pnode p2 = b->next;
	if (p1->num > p2->num)
	{
		head->next = p2;
		p2 = p2->next;
	}
	else
	{
		head->next = p1;
		p1 = p1->next;
	}
	pnode tmp = head->next;
	while (p1 != NULL && p2 != NULL)
	{
		if (p1->num > p2->num)
		{
			tmp->next = p2;
			p2 = p2->next;
		}
		else
		{
			tmp->next = p1;
			p1 = p1->next;
		}
		tmp = tmp->next;
	}
	if (p1 !=NULL)
	{
		tmp->next = p1;
	}
	if (p2 != NULL)
	{
		tmp->next = p2;
	}
	return head;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值