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) {
    	}
    };*/
    
  • 相关阅读:
    flushdb()
    del()
    删除匹配某个pattern的一组键
    I函数
    字段映射
    maven技术(一)软件安装与配置
    jQuery监听事件经典例子
    IE中调试JS的一款很好的工具
    技术大牛是如何拿到国内IT巨头offer的?
    bzoj2124 等差子序列(hash+线段树)
  • 原文地址:https://www.cnblogs.com/hesper/p/10443839.html
Copyright © 2011-2022 走看看