您的位置:首页 > 其它

6.2—排序—Merge Two Sorted Lists

2017-08-09 10:16 369 查看
描述

Merge two sorted linked lists and return it as a new list. e new list should be made by splicing

together the nodes of the first two lists.

#include<iostream>
using namespace std;
struct node
{
int data;
node *next;
};
class mylist
{
node *head;
public:
mylist()
{
head = new node();
head->next = NULL;
}
void CreateList(int a[], int n);
void Display();
friend void MergeSort(mylist &list1, mylist &list2);
~mylist();
};
void mylist::CreateList(int a[], int n)
{
node *p = head;
for (int i = 0; i < n; i++)
{
node *q = new node();
q->data = a[i];
p->next = q;
p = q;
}
p->next = NULL;
}
void mylist::Display()
{
node *p = head->next;
while (p)
{
cout << p->data << " ";
p = p->next;
}
cout << endl;

}
void MergeSort(mylist &list1, mylist &list2)
{
if (list1.head->next == NULL || list2.head->next == NULL)
return;
node *pre = list1.head;
node *p = list1.head->next;
node *q = list2.head->next;
list2.head->next = NULL;
while (p&&q)
{
if (p->data < q->data)
{
pre->next = p;
pre = p;
p = p->next;
}
else
{
pre->next = q;
pre = q;
q = q->next;
}
}
if (p)
pre->next = p;
if (q)
pre->next = q;

}
mylist::~mylist()
{
node *p = head;
while (p)
{
head = p->next;
delete p;
p = head;
}
}
int main()
{
const int n = 6;
const int m = 4;
int a
= { 3, 9, 15, 17, 21, 24 };
int b[m] = { 1, 4, 8, 9 };
mylist list1,list2;
list1.CreateList(a, n);
list2.CreateList(b, m);
//===
list1.Display();
list2.Display();
//===
MergeSort(list1, list2);
list1.Display();
list2.Display();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: