zoukankan      html  css  js  c++  java
  • 剑指offer(十六):合并两个排序的链表

    题目描述

    输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
    C++非递归实现:
    class Solution {
    public:
        ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
        {

          if(!pHead1)
            return pHead2;
          if(!pHead2)
            return pHead1;

            ListNode* pHead3 = new ListNode(0);
            ListNode * p1 = pHead1;
            ListNode * p2 = pHead2;
            ListNode * p3 = pHead3;
            while(p1&&p2){
                if(p1->val <= p2->val){
                    p3->next = p1;
                    p1 = p1->next;
                    p3 = p3->next;
                }
                else{
                    p3->next = p2;
                    p2 = p2->next;
                    p3 = p3->next;
                }
            }
            if(p1)
                p3->next = p1;
            if(p2)
                p3->next = p2;
            return pHead3->next;
        }
    };

    结果:

     Python递归实现:

    # -*- coding:utf-8 -*-
    # class ListNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.next = None
    class Solution:
        # 返回合并后列表
        def Merge(self, pHead1, pHead2):
            # write code here
            if pHead1 == None:
                return pHead2
            if pHead2 == None:
                return pHead1
            if pHead1.val <= pHead2.val:
                res = pHead1;
                res.next = self.Merge( pHead1.next, pHead2)
            else:
                res = pHead2;
                res.next = self.Merge( pHead1, pHead2.next)
            return res;

  • 相关阅读:
    Mysql锁机制介绍
    开启Mysql慢查询来优化mysql
    开启mysql慢查询日志并使用mysqldumpslow命令查看
    MySQL MyISAM/InnoDB高并发优化经验
    UIPageControl
    UIPikerView的属性
    UIScrollView
    UISement属性
    UISlide属性
    UISwitch
  • 原文地址:https://www.cnblogs.com/ttzz/p/13295527.html
Copyright © 2011-2022 走看看