15合并两个排序的链表
生活随笔
收集整理的這篇文章主要介紹了
15合并两个排序的链表
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目描述
輸入兩個單調遞增的鏈表,輸出兩個鏈表合成后的鏈表,當然我們需要合成后的鏈表滿足單調不減規則。 思路就是歸并算法的思路,注意首先判斷兩個鏈表節點都不為空,判斷大小while循環之后,要看哪個鏈表節點不為空,使用哨兵節點的方法處理頭節點。 /* struct ListNode {int val;struct ListNode *next;ListNode(int x) :val(x), next(NULL) {} };*/ class Solution { public:ListNode* Merge(ListNode* pHead1, ListNode* pHead2){if((pHead1 == nullptr) && (pHead2 == nullptr)){return nullptr;}if(pHead1 == nullptr){return pHead2;}if(pHead2 == nullptr){return pHead1;}ListNode* dummyhead = new ListNode(-1);ListNode* head = dummyhead;while(pHead1 != nullptr && pHead2 != nullptr){if(pHead1 -> val < pHead2 -> val){head -> next = pHead1;pHead1 = pHead1 -> next;}else{head -> next = pHead2;pHead2 = pHead2 -> next;}head = head -> next;}if(pHead1 != nullptr){head -> next = pHead1;}if(pHead2 != nullptr){head -> next = pHead2;}return dummyhead -> next;} };?
轉載于:https://www.cnblogs.com/dingxiaoqiang/p/7923010.html
總結
以上是生活随笔為你收集整理的15合并两个排序的链表的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Android 自定义WebView
- 下一篇: subprocess.Popen 运行w