设ha和hb分别是两个带头节点的费递减有序单链表的表头指针,设计以算法,将将两个有序链表合成一个非递减的有序单链表,该程序以以前发表的博客中的链表中的区别在与该立案表带有头结点

//头文件
#ifndef HEADLIST_H
#define HEADLIST_H

#include
using namespace std;
template
class LinkNode{

public:
	T data;
	LinkNode* link;
	LinkNode()
	{
		//默认构造函数
	}
	LinkNode(const T value, LinkNode* str = NULL)
	{
		data = value;
	}
};
template
class HeadList{

private:
	LinkNode* head;
	LinkNode* position = NULL;

public:
	HeadList();
	~HeadList();
	void setValue(T data);
	void print();
	void clear();
	void Merge(HeadList& str);



};
template
HeadList::HeadList()
{
	//该立案表拥有头结点,在头结点中不存放任何数据
	head = new LinkNode();
	head->link = NULL;
	position = head;
}
template
HeadList::~HeadList()
{
	clear();
}
template
void HeadList::setValue(T data)
{
	if (position == head)
	{
		LinkNode* p = head;
		p->link = new LinkNode(data);
		p = p->link;
		p->link = NULL;
		position = p;
	}
	else{
		LinkNode* p = position;
		if (data >= p->data)
		{
			p->link = new LinkNode(data);
			p = p->link;
			p->link = NULL;
			position = p;
		}
		else
			return;
	}
}
template
void HeadList::print()
{
	LinkNode* p = head;
	p = p->link;
	while (p)
	{
		cout << p->data << " ";
		p = p->link;
	}
	cout << endl;
}
template
void HeadList::clear()
{
	LinkNode* p = head;
	while (p)
	{
		p = p->link;
		delete head;
		head = p;
	}
	position = NULL;
}
template
void HeadList::Merge(HeadList& str)
{
	LinkNode* p = head;
	//因为头节点中都是不含数据的,所以从头结点后的一个节点开始
	LinkNode* pa = head->link;
	LinkNode* pb = str.head->link;
	//但两个链表中有一个到尾部后,结束循环
	while (pa&&pb)
	{
		//合并后的链表是非递减的
		if (pa->data <= pb->data)
		{
			p->link = pa;
			p = pa;
			pa = pa->link;
		}
		else
		{
			p->link = pb;
			p = pb;
			pb = pb->link;
		}
	}
	//判断哪一个链表未结束,直接连在p->link的后面
	p->link = pa ? pa : pb;
	//删除多余出来的头节点,不删除head是应为该函数未返回,且合并后的函数的头结点是head
	str.head->link = NULL;
	delete str.head;
	str.head = NULL;
}


#endif
//主函数
#include"HeadList.h"


int main(int argc, char argv[])
{
	HeadListlist;
	HeadListlist1;
	cout << "为单链表进行赋值,但输入的数据应不为0:" << endl;
	int number;
	cin >> number;
	while (number)
	{
		list.setValue(number);
		cin >> number;
	}
	list.print();
	cin >> number;
	while (number)
	{
		list1.setValue(number);
		cin >> number;
	}
	list1.print();
	list.Merge(list1);
	list.print();
	return 0;
}
阅读更多

没有更多推荐了,返回首页