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.
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(); }
相关文章推荐
- leetcode 21. Merge Two Sorted Lists(C语言,合并两个排序的链表为一个排序链表)32
- [C++]Merge Two Sorted Lists 归并两个排序的链表
- 165. 合并两个排序链表(merge-two-sorted-lists)(c++)----lintcode面试题之链表
- leetCode 21.Merge Two Sorted Lists (合并排序链表) 解题思路和方法
- [Leetcode] Merge two sorted lists 合并两已排序的链表
- Merge Two Sorted Lists(合并两个排序链表)
- LeetCode 21 Merge Two Sorted Lists(合并两个已排序的链表)(Linked List)
- Leetcode 21 Merge Two Sorted Lists 将两个已排序的链表合并起来
- 6.2 Merge Two Sorted Lists
- lintcode 容易题 :Merge Two Sorted Lists合并两个排序链表
- Leetcode 21:Merge Two Sorted Lists(golang实现合并两条已经排序的链表)
- LeetCode:21_Merge Two Sorted Lists | 合并两个排序列表 | Easy
- LeetCodet题解--21. Merge Two Sorted Lists(合并两个排序好的链表)
- Merge Two Sorted Lists 合并排序列表
- [leetcode] 【排序】 21. Merge Two Sorted Lists
- 2.【排序】Merge Two Sorted Lists--Accepted Java code
- LeetCode-21- Merge Two Sorted Lists(合并两个已排序链表)
- [Leetcode] Merge Two Sorted Lists
- leetcode 21. Merge Two Sorted Lists
- LeetCode-Merge Two Sorted Lists