【LeetCode】No.21 Merged Two Sorted Lists
阿新 • • 發佈:2018-11-20
題目:
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
Example:
Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4
即給定兩個已經排好序的連結串列,按照從大到小的順序將兩個連結串列中的元素合併成一個連結串列。
分析:
申請一個表頭,作為合併後的連結串列,然後同時遍歷兩個連結串列中的每一個節點,遍歷的同時對兩個連結串列中的節點進行比較,將其中數值較小的節點接到新申請的連結串列中。當其中一個連結串列為空時,則表示該連結串列已經遍歷完成;此時,若另一個連結串列的指標不為空,則說明該連結串列尚未被遍歷的元素一定都是大於第一個連結串列中的元素,且是有序排列的,則將該部分元素整體接到結果連結串列中即可。
程式:
#include <iostream> using namespace std; struct ListNode { int val; ListNode *next; ListNode(int x) :val(x), next(NULL) {} }; ListNode *CreateList(); void AddNode(ListNode *head, int element); void PrintList(ListNode *head); ListNode *MergeList(ListNode *l1, ListNode *l2); int main() { int element; ListNode *result; ListNode *l1 = CreateList(); ListNode *l2 = CreateList(); cout << "Please input the data of linklist:" << endl; /*新建兩個有序連結串列(帶表頭)*/ while (cin >> element) { AddNode(l1, element); if (cin.get() == '\n') { break; } } while (cin >> element) { AddNode(l2, element); if (cin.get() == '\n') { break; } } /*合併連結串列*/ cout << "The merged linklist : "; result = MergeList(l1, l2); PrintList(result); return 0; } /*建立空連結串列*/ ListNode *CreateList() { ListNode *head = new ListNode(-1); return head; } /*向表中新增結點*/ void AddNode(ListNode *head, int element) { if (!head) { cout << "The Linklist is NULL!"; exit(EXIT_FAILURE); } ListNode *tmp = head; while (tmp->next) { tmp = tmp->next; } ListNode *NewNode = new ListNode(element); tmp->next = NewNode; } /*列印連結串列*/ void PrintList(ListNode *head) { if (!head) { cout << "The Linklist is NULL!" << endl; exit(EXIT_FAILURE); } ListNode *p = head->next; while (p) { cout << p->val << " "; p = p->next; } cout << endl; } /*合併有序連結串列*/ ListNode *MergeList(ListNode *l1, ListNode *l2) { if (!l1 || !l2) return (l1 == NULL? l2 : l1); ListNode *p1 = l1->next; //不要表頭 ListNode *p2 = l2->next; ListNode *result = new ListNode(-1); ListNode *tmp = result; while (p1 && p2) { if (p1->val < p2->val) { tmp->next = p1; p1 = p1->next; } else { tmp->next = p2; p2 = p2->next; } tmp = tmp->next; } //if (p1) tmp->next = p1; //if (p2) tmp->next = p2; tmp->next = (p1 == NULL ? p2 : p1); return result; }