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;

  • 相关阅读:
    1032. Sharing (25)
    1031. Hello World for U (20)
    1030. Travel Plan (30)
    1029. Median (25)
    1028. List Sorting (25)
    1026. Table Tennis (30)
    win10 tortoiseSVN文件夹及文件图标不显示解决方法
    qrcode.react和jquery.qrcode生成二维码
    js来获取所有屏幕适配的总结
    handsontable整理
  • 原文地址:https://www.cnblogs.com/ttzz/p/13295527.html
Copyright © 2011-2022 走看看