概述
合并两个有序的单链表:
1.创建两个有序的单链表;
2.创建第三个链表来存放合并后的有序链表;
#include
using namespace std;
struct ListNode{
int value;
ListNode* next;
};
class CreateList
{
typedef ListNode Node;
public:
CreateList()
:pHead(NULL)
{}
void push(int _value)
{
Node* tp = pHead;
Node* temp = new Node();
if (!pHead)
{
pHead = temp;
pHead->value = _value;
pHead->next = NULL;
}
else
{
while (tp->next)
{
tp = tp->next;
}
tp->next = temp;
temp->value =_value;
temp->next = NULL;
}
}
Node* Combine(Node* ph1, Node* ph2)
{
if (ph1 == NULL)
{
return ph2;
}
if (ph2 == NULL)
{
return ph1;
}
Node* newHead = NULL;
Node* tail = NULL;
if (ph1->value < ph2->value)
{
newHead = ph1;
ph1 = ph1->next;
}
else
{
newHead = ph2;
ph2 = ph2->next;
}
tail = newHead;
while (ph1 && ph2)
{
if (ph1->value < ph2->value)
{
tail->next = ph1;
ph1 = ph1->next;
}
else
{
tail->next = ph2;
ph2 = ph2->next;
}
tail = tail->next;
}
if (ph1)
{
tail->next = ph1;
}
if (ph2)
{
tail->next = ph2;
}
return newHead;
}
void PrintList(Node* _pHead)
{
Node *p = _pHead;
while (p)
{
cout<
value<<"-> ";
p = p->next;
}
cout<<"NULL";
}
Node* pFristNode()
{
return pHead;
}
private:
Node* pHead;
};
int main()
{
CreateList l;
l.push(1);
l.push(2);
l.push(3);
l.push(4);
l.PrintList(l.pFristNode());
cout<
这里需要指出的是,给定测试的两个单链表要有序,如果无需则需要排序,将单链表变的有序。
最后
以上就是想人陪豌豆为你收集整理的合并两个有序的单链表的全部内容,希望文章能够帮你解决合并两个有序的单链表所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复