zoukankan      html  css  js  c++  java
  • 合并两个排序的链表

    合并两个排序的链表

    题目描述

    输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。

    归并排序的变形

    递归版

    class Solution {
    public:
        ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
        {
            ListNode *ret = NULL;
            
            if (NULL == pHead1) {
                return pHead2;
            }
            else if (NULL == pHead2) {
                return pHead1;
            }
            
            if (pHead1->val < pHead2->val) {
                ret = pHead1;
                ret->next = Merge(pHead1->next, pHead2);
            }
            else {
                ret = pHead2;
                ret->next = Merge(pHead1, pHead2->next);
            }
            
            return ret;
        }
    };
    

    非递归: 注意头结点保存方法, 先new一个节点做头结点, 归并后再delete

    class Solution {
    public:
        ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
        {
            ListNode *ret = new ListNode(0);
            ListNode *current = ret;
            
            while ((NULL != pHead1) && (NULL != pHead2)) {
                if (pHead1->val < pHead2->val) {
                    current->next = pHead1;
                    pHead1 = pHead1->next;
                }
                else {
                    current->next = pHead2;
                    pHead2 = pHead2->next;
                }
                current = current->next;
            }
            
            if (NULL == pHead1) {
                current->next = pHead2;
            }
            if (NULL == pHead2) {
                current->next = pHead1;
            }
            
            current = ret->next;
            delete ret;
            ret = current;
            
            return ret;
        }
    };
    
    /*
    struct ListNode {
    	int val;
    	struct ListNode *next;
    	ListNode(int x) :
    			val(x), next(NULL) {
    	}
    };*/
    
  • 相关阅读:
    a.default.ERROR.httpAjax is not a function
    Java heap space
    jmeter
    sql注入
    数据库查前三名
    maven
    国际化变现应用分析
    百度应用部署秘籍
    如何建立起一套有效的APP监控体系
    第三方舆情收集与质量闭环建设
  • 原文地址:https://www.cnblogs.com/hesper/p/10443839.html
Copyright © 2011-2022 走看看